Robert Down
Robert Down

Reputation: 147

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: 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

Upvotes: 9

Views: 16994

Answers (4)

Nguyen Hong Nhat
Nguyen Hong Nhat

Reputation: 61

.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>

Upvotes: 1

Johannes
Johannes

Reputation: 67778

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)

Upvotes: 12

Apurva Ojas
Apurva Ojas

Reputation: 331

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.)

Upvotes: 0

andreas
andreas

Reputation: 16936

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>

Upvotes: 19

Related Questions