Marcin Doliwa Marcin Doliwa - 4 months ago 9
HTML Question

Div with aspect ratio - how to center image inside of it?

I have 1:1 ratio div, and would like to center both vertically and horizontally image inside of it. How can I do this?



.main {
width: 200px;
}
.aspect-ratio-1-1 {
width:100%;
padding-top:100%;
position: relative;
}

.aspect-ratio-1-1 div {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color:orange;
}
}

<div class="main">
<div class="aspect-ratio-1-1">
<div>
<img src="http://placehold.it/150x100">
</div>
</div>
</div>




Answer

You can use a technique that works in virtually all browsers by setting the margin to auto, position to absolute, and the top/right/bottom/left to zero:

img {
  position:absolute;
  margin:auto;
  top:0;
  right:0;
  bottom:0;
  left:0;
}

.main {
  width: 200px;
}
.aspect-ratio-1-1 {
  width: 100%;
  padding-top: 100%;
  position: relative;
}
.aspect-ratio-1-1 div {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: orange;
}
img {
  position:absolute;
  margin:auto;
  top:0;
  right:0;
  bottom:0;
  left:0;
}
<div class="main">
  <div class="aspect-ratio-1-1">
    <div>
      <img src="http://placehold.it/150x100">
    </div>
  </div>
</div>

Another technique uses CSS3 transforms:

img {
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
  position: absolute;
}

.main {
  width: 200px;
}
.aspect-ratio-1-1 {
  width: 100%;
  padding-top: 100%;
  position: relative;
}
.aspect-ratio-1-1 div {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: orange;
}
img {
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
  position: absolute;
}
<div class="main">
  <div class="aspect-ratio-1-1">
    <div>
      <img src="http://placehold.it/150x100">
    </div>
  </div>
</div>

Comments