Profi660 Profi660 - 6 months ago 12
HTML Question

Css center any image in div

Lets say i have

div
with
width: 300px
and
height: 200px


I want any image inside this
div
to be centered both horizontally and vertically no matter if image is bigger or smaller than
div
;

For smaller images
margin: 0 auto
works well but higher image protrude to the right and isnt centered.

For bigger images works

height: 100%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);


I couldnt find any combination of those and didnt find any solution how to perfeclty center this image.

Answer

Add position: absolute to img and position: relative to div

.el {
  position: relative;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  margin: 50px 150px;
}
img {
  opacity: 0.4;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: absolute;
}
<div class="el">
  <img src="http://placehold.it/350x150">
  <img src="http://placehold.it/50x50/000000/ffffff">
</div>

@QUESTION AUTOR EDIT: i also added max-width: 100%; max-height:100% and works perfectly! (especially for reponsive styling)