How can I center an img
in a parent div
tag which is set to overflow: hidden
. That is, what I want is to clip the image but clip on both the left/right so the middle of the image is shown.
<div class='wrapper'>
<img/>
</div>
Then styles something like:
.wrapper {
position: absolute;
/* position details here */
overflow: hidden;
}
.wrapper img {
height: 100%;
margin-left: -??; //what here?
}
-50%
would be the width of the parent, but I want the width of the img itself.
Firefox supported CSS is acceptable.
http://codepen.io/gcyrillus/pen/BdtEj
use text-align , line-height , vertical-align and negative margin. img virtually reduced to zero, will center itself.
.wrapper {
width:300px;
text-align:center;
line-height:300px;
height:300px;
border:solid;
margin:2em auto;
overflow:visible; /* let's see what we slice off */
}
img {margin:-100%;vertical-align:middle;
/* to show whats been cut off */
position:relative;
z-index:-1;
}
For horizontal only :
.wrapper {
width:300px;
text-align:center;
border:solid;
margin:2em auto;
overflow:hidden
}
img {
margin:0 -100%;
vertical-align:middle;
}
Try to add
display:block;
margin:0px auto;
to ".wrapper img"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With