When using percentage values on padding, the percentage comes from the width of the containing element. This is true even when using a percentage for padding-bottom on an element with no height. With this knowledge and the formula for aspect ratio, you’ll be able to make sure that even when using an empty div, your height will maintain a smooth transition as screen sizes change. This formula is x1 / y1 * y2 = x2 which basically states, original height divided by original width multiplied by the new desired width will give you the new desired height.
Using the popular widescreen aspect ratio of 16:9, if our screen size was 1200 wide, our height would be 675px. But we don’t want to use pixels. Instead, we want to use percentages. So if we set our containing div to 1200px and our child div to 100%, the padding-bottom of that child element would have to be set to 56.25% to maintain that same aspect ratio.
9 / 16 * 1200(px) = 675(px)
9 / 16 * 100(%) = 56.25(%)
<div style=”max-width=1200px;”> <div style=”width:100%; padding-bottom:56.25%;”></div> </div>
As you can see above, our containing element’s max-width is 1200px (max-width to allow for responsiveness). The padding-bottom in its child element is set to 56.25% to maintain a 16:9 aspect ratio when scaling.
Now, using this padding-bottom trick with background-size: cover (CSS3), you’ll be able to scale the div as well as the image when it comes to smaller devices.
Stay tuned for more handy tips and tricks!
- CSS subpixel rendering
- 5 useful CSS tips for responsive design
- 5 tips to help you prepare for your responsive design site
- The subtler side of responsive design
- Resizing images in a browser: Proceed with caution
Questions or comments? Share them below, or tweet us @Pixafy!