'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
Solution 1:[1]
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>
Solution 2:[2]
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)
Solution 3:[3]
.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>
Solution 4:[4]
Just Add This in your CSS
Please Find your updated Fiddle below.
.out img{
margin: 0 auto;
max-width: 90%;
display: block;
}
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.)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | showdev |
| Solution 4 | Apurva Ojas |
