29 Apr

Preserve an HTML element’s aspect ratio

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 positioned absolute, relative or fixed position 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.
  • #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.
  • #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 #vertical to do the height
    • Top, bottom, left and right to 0 makes the element fit to the nearest offset parent which is #container.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *


6 + = ten

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>