【发布时间】:2017-09-16 21:50:29
【问题描述】:
如何使 div 以最大宽度和最大高度居中,同时保持其纵横比?
到目前为止,我的代码以 div 为中心,但它没有保持 6:5(高度:宽度)的纵横比
#main-content {
margin: 0 auto;
width: 100%;
max-width: 1200px;
height: 100%;
height: 500px;
background-color: #953d44;
position: relative;
}
#container {
width: 80%;
height: 80%;
max-height: 600px;
max-width: 500px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
position: absolute;
background-color: cornflowerblue;
}
<div id="main-content">
<div id="container"></div>
</div>
【问题讨论】:
-
研究关键词:padding-bottom hack
-
如果我向容器添加填充,一些奇怪的事情开始发生
-
@sanjihan 你检查过这个w3schools.com/howto/howto_css_aspect_ratio.asp
-
您需要将高度替换为填充。如果你希望这个元素不仅仅是一个有背景的正方形,而是在其中放置实际内容,那么你必须绝对定位内容。
-
max-height 在使用填充时会被忽略。我添加了 box-sizing:border-box。结果相同。