0

I want the div with red background to resize according to the browser width while keeping its aspect ratio as 16:9 but not exceed the height of 300px. I also want the text written in the div to align at the center; both vertically and horizontally. Through the following CSS code, the div is resizing according to the aspect ratio and the text is horizontally aligned. But the div is not limiting its height to 300px and the text is not vertically aligning.

.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>
Sumit patel
  • 3,807
  • 9
  • 34
  • 61
  • [http://stackoverflow.com/questions/1495407/maintain-the-aspect-ratio-of-a-div-with-css](http://stackoverflow.com/questions/1495407/maintain-the-aspect-ratio-of-a-div-with-css) – Bhushan wagh Feb 21 '17 at 04:33
  • http://stackoverflow.com/questions/1495407/maintain-the-aspect-ratio-of-a-div-with-css – Bhushan wagh Feb 21 '17 at 04:34
  • did same thing. aspect ration is maintaining but the division is not following max-height. Also, I want to align text vertically center – Mukund Mittal Feb 21 '17 at 04:36

1 Answers1

1

Check the snippet.

.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>
Rahul
  • 2,011
  • 3
  • 18
  • 31
  • I want the division to maintain its aspect ratio. In this code, the height of the division is not changing – Mukund Mittal Feb 21 '17 at 07:31
  • Look clearly you set `max-heigh: 300px;` That means `height` will not bigger than `300px`. I just set a bigger `height` for demo. You can set `300px height`. Your children element `display` is `table-cell` so you should be set a `fixed height` for your parent `display` `table` element. Then set `min-height` and `max-height` it will help you the `height` will not smaller than `min-height and `height` will not bigger than `max-height`. – Rahul Feb 21 '17 at 08:27