Tuesday, February 17, 2015

Constant aspect ratio element

You can create containers that maintain a constant aspect ratio by using padding-bottom as a percentage. The CSS spec says that padding-bottom is defined relative to the *width*, not height, so if you want a 5:1 aspect ratio container you can do something like this:

<div style="width: 100%; position: relative; padding-bottom: 20%;">
<div style="position: absolute; left: 0; top: 0; right: 0; bottom: 0;">
this content will have a constant aspect ratio that varies based on the width.

This is useful for responsive layouts where you want the width to adjust dynamically but want to keep, say, square photo thumbnails.

No comments:

Post a Comment