我试图保持div
元素的特定比例(比如1:2),但保持宽度小于200px.
到目前为止我得到了什么:
div {
width: 100%;
height: 0;
padding-bottom: 50%;
max-width: 200px;
}
Run Code Online (Sandbox Code Playgroud)
它不起作用 - 如果我展开窗口,宽度停止扩展200px但高度不断增长!
我试过设置box-sizing: border-box
和max-height: 100px
,但既不工作.
我该怎么办?
这是一个小提琴:http://jsfiddle.net/WVu3s/
这是一个基于本文代码的纯 CSS 解决方案,但有一些细微的更改:
超文本标记语言
<div class = "box">
<div class = "content">Ratio 1:2</div>
</div>
Run Code Online (Sandbox Code Playgroud)
CSS
/* Box styles */
.box {
width: 100%;
position: relative;
display: inline-block;
max-width:200px; /* max width of the box */
}
.box:after {
padding-top: 50%; /*1:2 ratio*/
display: block;
content: '';
}
/* Style that should be applied to the box content */
.content {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
background-color: green;
}
Run Code Online (Sandbox Code Playgroud)
这是一个演示