Reputation: 329
Can I set height in CSS using the width? This is what I have now:
width: 22.5%;
height: width*2.25;
background: #fff url("images/image_bg.png");
background-repeat: no-repeat;
background-size: cover;
border: 0.5px solid #ddd;
The width of the divs are always the same, but the hights have very slight differences, which makes the backgrounds for them not fit properly. If I can set the hight to scale with the width it would be perfect.
Upvotes: 5
Views: 11672
Reputation:
padding
...
Percentages: refer to width of containing block
http://www.w3.org/TR/CSS2/box.html#propdef-padding-right
A little known, but very useful, trick with the padding property is that, if the value provided is a percentage, the computed value will be a percentage of the computed width of the containing block
To keep the aspect ratio intact, use padding-bottom: X%
.
If you want the height to be the same as the width and the width is set to 25% (of the containing block) then then you would set padding-bottom: 25%
on the element.
If you want the height to be half of the width and the width is 25% (of the containing block) then you would set padding-bottom: 12.5%
If you want the height to be 2.25 times the width and the width is 22.5% then multiply that percentage by 2.25 which gives you 56.25% and apply that percentage e.g.
padding-bottom: 56.25%
#keep-ratio {
width: 22.5%; /* 22.5% of the parent's width*/
padding-bottom: 56.25%; /* (25% of the parent's width) * 2.25 */
background: #fff url("//lorempixel.com/400/400");
background-repeat: no-repeat;
background-position: center center;
background-size: cover;
border: 0.5px solid #ddd;
}
<div id="keep-ratio"></div>
Upvotes: 8