Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Web Technology by (20.3k points)

I want to create a div that can change its width/height as the window's width changes.

Are there any CSS3 rules that would allow the height to change according to the width while maintaining its aspect ratio?

I know I can do this via JavaScript, but I would prefer using only CSS.

1 Answer

0 votes
by (40.7k points)

Try to create a wrapper <div> with a percentage value for padding-bottom, this way:

div {

  width: 100%;

  padding-bottom: 75%;

  background: gold; /** <-- For the demo **/

}

<div></div>

 Note: This will result in a <div> with height equal to 75% of the width of its container (i.e. a 4:3 aspect ratio).

The percentage will be calculated with respect to the width of the generated box's containing block [...]. 

Following are the Padding-bottom values for other aspect ratios and 100% width :

aspect ratio  | padding-bottom value

--------------|----------------------

    16:9      |       56.25%

    4:3       |       75%

    3:2       |       66.66%

    8:5       |       62.5%

To keep the aspect ratio of the div and prevent its content from stretching it, you just need to add an absolutely positioned child and stretch it to the edges of the wrapper with:

You can try placing content in the div like this:

div.stretchy-wrapper {

  position: relative;

}

div.stretchy-wrapper > div {

  position: absolute;

  top: 0; bottom: 0; left: 0; right: 0;

}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...