【问题标题】:Center div with max-width and height enabled and maintain aspect-ratio启用最大宽度和高度的中心 div 并保持纵横比
【发布时间】: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>

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

【问题讨论】:

  • 研究关键词:padding-bottom hack
  • 如果我向容器添加填充,一些奇怪的事情开始发生
  • 您需要将高度替换为填充。如果你希望这个元素不仅仅是一个有背景的正方形,而是在其中放置实际内容,那么你必须绝对定位内容。
  • max-height 在使用填充时会被忽略。我添加了 box-sizing:border-box。结果相同。

标签: html css


【解决方案1】:

你没有注意到这个变化,因为主容器本身只有 500px 的高度。我已将其更改为 1000 像素。

运行下面的sn-p,进入全屏模式,果然有效!

#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 这将不起作用。

【讨论】:

    猜你喜欢
    • 2015-01-21
    • 2021-02-09
    • 2015-06-13
    • 2019-03-17
    • 2014-07-01
    • 2014-02-06
    • 1970-01-01
    • 2015-05-22
    • 2021-06-23
    相关资源
    最近更新 更多