CSS-根据宽度设置高度 [英] CSS - Set height according to width

查看:60
本文介绍了CSS-根据宽度设置高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

div的宽度总是相同的,但是高点的差别很小,这使得它们的背景不合适.如果我可以将高度设置为与宽度成比例,那将是完美的.

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.

推荐答案

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

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

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

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

  • 如果您希望高度宽度相同,并且宽度设置为 25%(包含块的),然后您将在元素上设置 padding-bottom:25%.

  • 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.

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

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%

如果您希望高度 2.25 乘以宽度,而宽度 22.5%,然后将该百分比乘以 2.25 ,得出 56.25%并应用该百分比,例如
padding-bottom:56.25%

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>

这篇关于CSS-根据宽度设置高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆