Profi660 Profi660 - 6 months ago 12
HTML Question

Css center any image in div

Lets say i have

width: 300px
height: 200px

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

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.


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="">
  <img src="">

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