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 this to happen (centered in the x-direction, the black square is the image and the red square is the div class): http://i.imgur.com/9QGVYtN.png

Output Result: http://i.imgur.com/EqzM7QO.png

+4
source share
4 answers

This behavior can be achieved using the image as a background. Just set background-size: cover;and background-position: center;to fill the container with the image and place 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>
Run codeHide result

<img />, 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>
Hide result
+7

CSS:

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

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

50% 50% , .

: , margin-left: -50%;, , , : 500 , 100 )

+2

.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>
Hide result
+1

CSS

, .

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

: margin:0 auto; 0 ( .)

0

Source: https://habr.com/ru/post/1657258/


All Articles