Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

center image in div with overflow hidden

Tags:

html

css

center

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/

like image 227
Puyol Avatar asked May 31 '12 09:05

Puyol


People also ask

How do I center an image overflow in CSS?

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

How do I keep an image centered in a div?

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.

How do I center an image in stackoverflow?

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!


1 Answers

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/

like image 70
Jaap Avatar answered Oct 11 '22 13:10

Jaap