I have an image of 400px and a div that is smaller (the width is not always 300px as in my example). I want to center the image in the div, and if there is an overflow, hide it.
Note: I must keep the position:absolute
on the image. I'm working with css-transitions, and if I use position:relative
, my image shakes a bit (https://web.archive.org/web/20120528225923/http://ta6.maxplus.be:8888/).
jsfiddle http://jsfiddle.net/wjw83/1/
It is pretty easy to do if the image is smaller than the surrounding div: margin-left: auto; margin-right: auto; display: block; But when the image is larger than the div it simply starts at the left edge and is off center to the right (we are using overflow: hidden ).
Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.
You can use text-align: center on the parent and change the img to display: inline-block → it therefore behaves like a text-element and is will be centered if the parent has a width!
You should make the container relative and give it a height as well and you're done.
http://jsfiddle.net/jaap/wjw83/4/
.main { width: 300px; margin: 0 auto; overflow: hidden; position: relative; height: 200px; } img.absolute { left: 50%; margin-left: -200px; position: absolute; }
<div class="main"> <img class="absolute" src="http://via.placeholder.com/400x200/A44/EED?text=Hello" alt="" /> </div> <br /> <img src="http://via.placeholder.com/400x200/A44/EED?text=Hello" alt="" />
If you want to you can also center the image vertically by adding a negative margin and top position: http://jsfiddle.net/jaap/wjw83/5/
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