我可以将div高度编程为当前宽度的某个百分比吗?

Bar*_*art 5 html css alignment css3

是否可以给div一个宽度,该宽度是窗口的百分比,高度是它当前宽度的某个百分比?因此div调整大小,但在调整浏览器窗口大小时保持相同的宽高比.

谢谢Ciao

LcS*_*zar 6

padding诀窍,已经回答了,但我使用另一种方法,包含两个嵌套的div.

父母一个,我设置了宽度.孩子一,我使用height值作为容器单位vw- (意味着视口宽度).

效果很好,请看这里(调整视口大小)

<div>
    <div></div>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS:

div {
    width: 100%;
}

div > div {
    background: silver;
    height: 10vw;
}
Run Code Online (Sandbox Code Playgroud)


Tod*_*odd 5

我用这个

演示1

.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%
}
Run Code Online (Sandbox Code Playgroud)

演示2

如果你不喜欢我,你可以做一个混合:

.aspectRatio(@widthAspect, @heightAspect) {
    @aspect: @heightAspect/@widthAspect * 100;
    max-width: 100%;

    &:before {
        content: '';
        display: block;
        width: 100%;
        padding-bottom: ~"@{aspect}%";
    }
}
Run Code Online (Sandbox Code Playgroud)