Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show middle of image in div using css?

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: http://i.imgur.com/gYzP1xo.png

But I want to get it like this (centered in x-direction, black square is image and red square is div class out): http://i.imgur.com/9QGVYtN.png

The output result is: http://i.imgur.com/EqzM7QO.png

like image 282
Robert Down Avatar asked Oct 10 '16 10:10

Robert Down


1 Answers

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>
like image 196
andreas Avatar answered Oct 20 '22 09:10

andreas