sanjihan
sanjihan

Reputation: 6046

Center div with max-width and height enabled and maintain aspect-ratio

How can I center a div with max-width and max height, but also maintain it's aspect ratio?

My code so far centers div, but it does not maintain aspect ratio of 6:5 (height:width)

#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

Upvotes: 1

Views: 316

Answers (1)

Jones Joseph
Jones Joseph

Reputation: 4948

You couldnt notice the change because the main container itself had only 500px height. I have changed it to 1000px.

Run the following snippet and goto full screen mode, It actually works!

#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 this wont work if main container height is less then the max height specified for the contanier.

Upvotes: 1

Related Questions