是否可以给div一个宽度,该宽度是窗口的百分比,高度是它的当前宽度的某个百分比?因此div调整大小,但在调整浏览器窗口大小时保持相同的宽高比。
由于 侨
答案 0 :(得分:6)
padding
诀窍已经回答了,但我使用了另一种方法,包含了两个嵌套的div。
父母,我设定宽度。孩子一,我使用height
值作为容器单位vw
- (表示视口宽度)。
It works well, see here(调整视口大小)
<div>
<div></div>
</div>
CSS:
div {
width: 100%;
}
div > div {
background: silver;
height: 10vw;
}
答案 1 :(得分:5)
我用这个
.aspect-ratio {
max-width: 100%;
}
.aspect-ratio:before {
content: '';
display: block;
width: 100%;
padding-bottom: ({height-aspect} / {width-aspect} * 100)%; // for 3 x 4, for instance: 75%
}
如果你不喜欢我,你可以做一个混音:
.aspectRatio(@widthAspect, @heightAspect) {
@aspect: @heightAspect/@widthAspect * 100;
max-width: 100%;
&:before {
content: '';
display: block;
width: 100%;
padding-bottom: ~"@{aspect}%";
}
}
答案 2 :(得分:3)
如果以百分比设置元素的顶部和底部填充,则它将相对于元素的宽度。
答案 3 :(得分:2)
在height
中使用百分比时,会根据生成的包含块的高度来计算。
由于您要根据宽度计算它,因此您可以使用padding-top
。
为避免影响内容,请将它们放在绝对定位的包装中。
#wrapper {
padding-top: 25%; /* ratio */
border: 1px solid;
position: relative;
}
#content {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
&#13;
<div id="wrapper">
<div id="content">
<p>Foo</p>
<p>Bar</p>
<p>Baz</p>
</div>
</div>
&#13;
答案 4 :(得分:0)
是的,使用jquery,您可以获得屏幕宽度和高度,然后您可以定位该div并设置高度和宽度