CSS, HTML

Building responsive and fixed aspect containers with HTML and CSS

Here’s a simple way to build containers that maintain aspect ratio as screen size changes.
The cool thing with this method is that there is no need to know actual sizes

The basic trick we are going to use for this demo is Percentage (%) based padding on elements. The important thing to realize is that % based padding is based on the WIDTH of the element CONTAINER.

So lets put together a simple example. The Blue Border represents the container box. The red background represents the box we want to maintain aspect. For the full css you can use your browser inspect tool.

// lets look at some basic css
.example-137 .container1 { border: 5px solid blue; }
.example-137 .container2 { width: 50%; border: 5px solid blue; }
.example-137 .fixedBox1, .example-137 .fixedBox2, .example-137 .fixedBox3 { background-color: red; }
16:9
4:3
1:1
16:9
4:3
1:1

Now, lets create three ratios for our boxes.

1.) 16:9
2.) 4:3
3.) 1:1

Now we’ll be working with percentages, so we use the simple formula of WIDTH / HEIGHT = WIDTH / HEIGHT. Then we solve this simple equation.

// math formula breakdown
knownWidth / knownHeight = knownWidth / knownHeight
// we know 3 of these values and then we solve

// 16:9
16 / 9 = 100(%) / height
height = (100 * 9) / 16
height = 56.25 (%)

// 4:3
4 / 3 = 100 / height
height = (100 * 3) / 4
height = 75 (%)

// 1:1
21 / 9 = 100 / height
height = (1 * 1) / 1
height = 100 (%)

 

Now, we can use these values as a padding-top value.

// our updated CSS
.example-137.withUpdatedPadding .fixedBox1 { height: 0; padding-top: 56.25%; }
.example-137.withUpdatedPadding .fixedBox2 { height: 0; padding-top: 75%; }
.example-137.withUpdatedPadding .fixedBox3 { height: 0; padding-top: 100%; }
16:9
4:3
1:1
16:9
4:3
1:1
Shares