Ever wondered how to preserve an element’s aspect ratio? Take this markup:
<div id="container">
<div id="vertical">
<div id="ratioElement">content</div>
</div>
And this CSS:
#container{
position:relative;
float:left;
width:100%;
}
#vertical{
margin-top:50%; /* 2:1 ratio, container width : vertical margin */
}
#ratioElement{
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
background:#069;
}
Explanation:
#container– provides a container and the width of the ratio’ed element- Relative position makes it a “positioned element”, but unlike
absolute, it does not take the element out of the flow. This makes any descendant that is positionedabsolute,relativeorfixedposition relative to this element. - Floating the container left makes the container shrink-wrap the content, making the container wrap snugly to the content. Display inline-block does the same thing also.
- Setting a width gives a baseline measurement of the ratio and will be the basis of our element’s width. Actually, it could be any value. I just placed
100%so that it fills the parent container.
- Relative position makes it a “positioned element”, but unlike
#vertical– provides the height of the ratio’ed element- The top margin gives the element its height. It get’s it’s baseline for the percentage from the width of the parent, which is
#container(weird eh?). So if the parent width shrinks, the margin of this element also shrinks. This should be a percentage value.
- The top margin gives the element its height. It get’s it’s baseline for the percentage from the width of the parent, which is
#ratioElement– the element to preserve ratio- Position absolute removes the element from the flow, positioning it relative to the nearest offset parent which is
#container. Taken out of the flow, it does not affect the container’s dimensions, leaving#verticalto do the height Top,bottom,leftandrightto0makes the element fit to the nearest offset parent which is#container.
- Position absolute removes the element from the flow, positioning it relative to the nearest offset parent which is
So in the end, if the container width shrinks, the element’s width and vertical’s height shrinks. When vertical’s height shrinks, the height of the element also shrinks. Now we have preserved our aspect ratio.





