首页 文章

启用最大宽度和高度的中心div并保持纵横比

提问于
浏览
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

1 回答

  • 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如果主容器高度小于为指示器指定的最大高度,这将不起作用 .

相关问题