使用CSS保持div的高宽比 [英] Maintain the aspect ratio of a div with CSS

查看:341
本文介绍了使用CSS保持div的高宽比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个div,可以随着窗口宽度的变化而改变其宽度/高度。



有任何CSS3规则允许高度根据



我知道我可以通过JavaScript来实现,但我宁愿只使用CSS。

解决方案

只需使用 padding-bottom 的百分比值创建一个包装器< div> this:



< pre class =snippet-code-css lang-css prettyprint-override> div {width:100%;填充底部:75%;背景:金; / **< - 对于演示** /}

 < div>< / div>  



导致< div> ,其高度等于其容器宽度的75%(4:3宽高比)。



这取决于以下事实:对于填充:


百分比是相对于生成的框的包含块[...](来源: w3.org ,强调我的)


其他宽高比和100%宽度的底部值: p>

 宽高比| padding-bottom value 
-------------- | ----------------------
16 :9 | 56.25%
4:3 | 75%
3:2 | 66.66%
8:5 | 62.5%








为了保持div的宽高比并防止它的内容被拉伸,你需要添加一个绝对定位的孩子,包装器的边缘:

  div.stretchy-wrapper {
position:relative;
}

div.stretchy-wrapper> div {
position:absolute;
top:0; bottom:0; left:0; right:0;
}

演示 和另一个更深入的演示


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.

解决方案

Just create a wrapper <div> with a percentage value for padding-bottom, like this:

div {
  width: 100%;
  padding-bottom: 75%;
  background:gold; /** <-- For the demo **/
}

<div></div>

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

This relies on the fact that for padding :

The percentage is calculated with respect to the width of the generated box's containing block [...] (source: w3.org, emphasis mine)

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%


Placing content in the div :

In order to keep the aspect ratio of the div and prevent it's content from stretching it, you need to add an absolutely positioned child and stretch it to the edges of the wrapper with:

div.stretchy-wrapper {
  position: relative;
}

div.stretchy-wrapper > div {
  position: absolute;
  top: 0; bottom: 0; left: 0; right: 0;
}

Here's a demo and another more in depth demo

这篇关于使用CSS保持div的高宽比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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