Div with set aspect ratio and vertically and horizontally centered content?

Viewed 524

I am trying to create a div with a width of 60% of its parent div, and a height that is 40% of its own width. The div must keep this aspect ratio.

The div should contain text (more than one line) that is both vertically and horizontally centered.

I cannot use JS for this, only HTML and CSS.

I have tried the top/bottom padding trick for creating a div with a given aspect ratio, which works, however I am not able to center the text vertically.

The following snippet example looks as desired, only without the fixed aspect ratio.

.container {
  width: 80%;
  background: grey;
}

.ratio {
  background: white;
  margin: 0px auto 0px auto;
  width: 60%;
  height: 300px; /* Should be 40% of width */
  
  display: flex;
  justify-content: center;
  align-content: center;
  flex-direction: column;
}

.text {
  text-align: center;
}
<div class="container">
  <h2>
    Heading
  </h2>
  <div class="ratio">
    <div class="text">
      Lorem ipsum dolor sit amet, ea mel case eros lorem. In etiam aperiam consetetur vix, ex duis postulant intellegam eam, alienum officiis antiopam duo cu. Cum et dico hinc iudicabit, sonet senserit petentium ex cum, ex usu intellegam theophrastus.
    </div>
  </div>
  <p>
    Other content
  </p>
</div>

2 Answers

You can use the padding trick and then make the element out of the flow so it won't get affect by the padding:

.container {
  width: 80%;
  background: grey;
}

.ratio {
  background: white;
  margin: 0px auto 0px auto;
  width: 60%;
  padding-top:40%;
  position:relative;
}

.text {
  text-align: center;
  position:absolute;
  top:50%;
  transform:translateY(-50%);
}
<div class="container">
  <h2>
    Heading
  </h2>
  <div class="ratio">
    <div class="text">
      Lorem ipsum dolor sit amet, ea mel case eros lorem. In etiam aperiam consetetur vix, ex duis postulant intellegam eam, alienum officiis antiopam duo cu. Cum et dico hinc iudicabit, sonet senserit petentium ex cum, ex usu intellegam theophrastus.
    </div>
  </div>
  <p>
    Other content
  </p>
</div>

You can use javascript/jQuery to set that specific height:

$('.ratio').height($('.ratio').width()*.4);
Related