【问题标题】:Div to keep its aspect ratio and not exceed certain height. The text inside it should be vertically and horizontally centeredDiv 保持其纵横比并且不超过一定的高度。里面的文字应该垂直和水平居中
【发布时间】:2017-07-10 13:30:16
【问题描述】:

我希望红色背景的 div 根据浏览器宽度调整大小,同时保持其纵横比为 16:9 但不超过 300px 的高度。我还希望 div 中写入的文本居中对齐;垂直和水平。通过下面的 CSS 代码,div 正在根据纵横比调整大小,并且文本是水平对齐的。但是 div 并没有将其高度限制为 300px,并且文本没有垂直对齐。

.container {
  background-color: red;
  position: relative;
  width: 100%;
  max-height: 300px;
  padding-top: 56.25%;
  /* 16:9 Aspect Ratio */
  display: table;
}

.text {
  display: table-cell;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  text-align: center;
  vertical-align: middle;
  font-size: 20px;
  color: white;
}
<h2>Maintain Aspect Ratio 16:9</h2>

<div class="container">
  <div class="text">This is some text...</div>
</div>

【问题讨论】:

标签: html css twitter-bootstrap vertical-alignment aspect-ratio


【解决方案1】:

检查sn-p。

.container {
  background-color: red;
  position: relative;
  width: 100%;
  max-height: 300px;
  height: 500px;
  /*padding-top: 56.25%;*/
  /* 16:9 Aspect Ratio */
  display: table;
}

.text {
  display: table-cell;
  /*position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;*/
  text-align: center;
  vertical-align: middle;
  font-size: 20px;
  color: white;
  height: 100%;
  width: 100%;
}
<h2>Maintain Aspect Ratio 16:9</h2>

<div class="container">
  <div class="text">This is some text...</div>
</div>

【讨论】:

  • 我希望分区保持其纵横比。在这段代码中,分割的高度没有改变
  • 看清楚你设置了max-heigh: 300px; 这意味着height 不会大于300px。我只是为演示设置了一个更大的height。您可以设置300px height。你的子元素display 是table-cell,所以你应该为你的父元素displaytable 设置一个fixed height。然后设置min-height 和max-height 它会帮助你height 不会小于min-height and height`不会大于max-height。
猜你喜欢
  • 1970-01-01
  • 2018-02-16
  • 2015-01-03
  • 2021-06-19
  • 2019-05-21
  • 1970-01-01
  • 1970-01-01
  • 2014-12-13
相关资源
最近更新 更多