Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
826 views
in Technique[技术] by (71.8m points)

html - 使用CSS保持div的长宽比(Maintain the aspect ratio of a div with CSS)

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

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

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

(是否有任何CSS3规则可以允许高度根据宽度改变, 同时保持其长宽比 ?)

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

(我知道我可以通过JavaScript来做到这一点,但我宁愿只使用CSS。)

div根据窗口宽度保持宽高比

  ask by jackb translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

(只需为padding-bottom创建具有百分比值的包装器<div> ,如下所示:)

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

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

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)

(相对于生成的盒子的包含块的宽度计算百分比(来源: w3.org ,强调我的))

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

(其他长宽比和100%宽度的填充底部值:)

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 :

(将内容放在div中:)

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

(为了保持div的长宽比并防止其内容拉伸,您需要添加一个绝对定位的子级,并使用以下方法将其拉伸到包装的边缘:)

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

(这是一个演示 ,还有另一个更深入的演示)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...