Responsive element width based on its height without JavaScript - Cobbled Code

Maintaining an element’s aspect ratio by changing its height based on its width is a breeze using the trusty old CSS padding-bottom trick.

This doesn’t work when you need to maintain the aspect ratio of an element based on its height 😭.

But stackoverflow:


<div class="container">
<div class="content">My Cool Content!</div>


.container {
	position: relative;
	display: inline-block;
	// The height of the container.
	height: 200px;

.container > img {
	// How wide should the container be
	// as a percentage of its width?
	height: 100%;

.content {
	position: absolute;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;

💖 it + bonus points because it uses a spacer.gif.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.