Maintaining aspect ratio with CSS

Posted by on Sep 19, 2016 in Code Chat | No Comments
Maintaining aspect ratio with CSS

There are occasion when you don’t want the size of a box to flow with the page content.

For example, when you’re building a page of tiled content, you may want to make sure all of the tiles are the same size, but you can’t fix the height and width because the size must be fluid in relation to the size of the page.

4030e83e34a8eb7c79174246298a7799

Fixed aspect ratio

For example, we may want to make sure that each tile is 25% of the page width and always has an aspect ration of 4:3.

We can’t rely on the content of each box to determine the size, because the content is dynamic. So how do we accomplish this?

Pseudo tags

We use the “:before” pseudo tag to create an empty element which will determine the size of the box.

We can fix the aspect of this pseudo tag by giving it a width of 100% and a padding-top value relating to the aspect.

The rest of the content in the box should be absolutely positioned, so that it doesn’t affect the size of the box.


.tile{
position:relative;
float:left;
width:25%;
border:solid #000 1px;
}
.tile:before{
content:'';
display:block;
width:100%;
padding-top:75%;
}
.tile .tile-contnt{
position:absolute;
}

Leave a Reply