2017-04-20 112 views
0

如何居中最大寬度和最大高度的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>

https://codepen.io/timsim/pen/dWMbqR

+0

研究關鍵字:填充底劈如果我添加填充到容器 – CBroe

+0

,一些奇怪的東西開始發生 – sanjihan

+0

@sanjihan你檢查這https://www.w3schools.com/howto/howto_css_aspect_ratio.asp –

回答

0

你不可能注意到的變化因爲主容器本身的高度只有500px。我已將其更改爲1000px。

運行以下代碼片段並轉到全屏模式,它實際上工作!

#main-content { 
 
    margin: 0 auto; 
 
    width: 100%; 
 
    max-width: 1200px; 
 
    height: 100%; 
 
    height: 1000px; 
 
    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>

P.S:OFC如果主容器高度這不會工作不到的contanier規定的最大高度。

相關問題