CSS - 根据宽度设置高度

Mit*_*ol1 5 html css

我可以在 CSS 中使用宽度设置高度吗?这就是我现在所拥有的:

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;
Run Code Online (Sandbox Code Playgroud)

div 的宽度始终相同,但高度有非常细微的差异,这使得它们的背景不合适。如果我可以将高度设置为与宽度成比例,那就完美了。

小智 8

padding
...
百分比:参考包含块的宽度
http://www.w3.org/TR/CSS2/box.html#propdef-padding-right

padding 属性的一个鲜为人知但非常有用的技巧是,如果提供的值是百分比,则计算值将是包含块的计算宽度的百分比

要保持纵横比不变,请使用padding-bottom: X%.

  • 如果您希望高度与宽度相同,并且宽度设置为(包含块的) 25%,那么您可以padding-bottom: 25%在元素上进行设置。

  • 如果您希望高度宽度的一半,宽度是(包含块的)25% ,那么您可以设置padding-bottom: 12.5%

  • 如果您希望高度宽度的2.25倍,宽度22.5%,则将该百分比乘以2.25 ,得到56.25%并应用该百分比,例如
    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;
}
Run Code Online (Sandbox Code Playgroud)
<div id="keep-ratio"></div>
Run Code Online (Sandbox Code Playgroud)