How to show middle of image in div using css?
Asked Answered
E

4

9

How to show middle of image in div using css ?

https://jsfiddle.net/yn7hubkd/

CSS:

.out{
    width: 500px;
    height: 500px;
    overflow: hidden;
}

HTML:

<div class="out">
  <img src="https://redditupvoted.files.wordpress.com/2016/03/waffles-cat.jpg">
</div>

I get this output: https://i.sstatic.net/o59iI.png

But I want to get it like this (centered in x-direction, black square is image and red square is div class out): https://i.sstatic.net/4dT5a.png

The output result is: https://i.sstatic.net/aHgCc.png

Ebby answered 10/10, 2016 at 10:4 Comment(0)
H
19

This behaviour can simply be achieved by using the image as background. Just set background-size: cover; and background-position: center; to fill the container with the image and position it in the center:

.out {
  width: 500px;
  height: 500px;
  overflow: hidden;
  background-image: url(https://redditupvoted.files.wordpress.com/2016/03/waffles-cat.jpg);
  background-size: cover;
  background-position: center;
}
<div class="out"></div>

In case that you are forced to use the <img /> tag, simply add a negative left margin of 50%:

.out {
  width: 500px;
  height: 500px;
  overflow: hidden;
}
.out img {
  margin-left: -50%;
}
<div class="out">
  <img src="https://redditupvoted.files.wordpress.com/2016/03/waffles-cat.jpg">
</div>
Helm answered 10/10, 2016 at 10:6 Comment(2)
I have to use img tagEbby
Please note: This (second solution) only works because in this particular case the image is exactly twice as wide as the container. Otherwise you need a bit more (see my answer)Gravestone
G
12

You can center it with this CSS rule:

.out img {
  position: relative;
  left: 50%;
  transform: translateX(-50%);
}

https://jsfiddle.net/456jLdfx/1/

That places it at 50% width of the container and moves it back to the left by 50% of its own width, thereby centering it horizontally.

An additional note: This works for any image width, as opposed to margin-left: -50%;, which only works in this case because the image is exactly twice as wide as the container: 500px container, 100px image)

Gravestone answered 10/10, 2016 at 10:10 Comment(1)
Over 4 years old and still giving me the best solution. Thanks man!Visibility
M
1

.out {
  width: 500px;
  height: 500px;
  overflow: hidden;
  background: url('https://redditupvoted.files.wordpress.com/2016/03/waffles-cat.jpg') center center;
}
<div class="out"></div>
Mikamikado answered 10/10, 2016 at 10:11 Comment(0)
T
0

Just Add This in your CSS

Please Find your updated Fiddle below.

.out img{
  margin: 0 auto;
  max-width: 90%;
  display: block;
}

Your Updated Fiddle

Expalnation: margin:0 auto; adjust the block level element margin top and bottom to 0 and left and right auto (i.e it will calculate automatically relative to parent.)

Tint answered 10/10, 2016 at 10:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.