Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

center image horizontally inside overflow:hidden div

Tags:

css

I have a parent div with width:100% and overflow:hidden
I need to place an image of 2500-3000px inside it, but have the image horizontally centered (cropped left and right) so the main center section of the image shows on smaller screens, but without horizontal scrollbar.
I can't use background-image since the image is dynamically added via php.
Please help.

like image 880
user1078494 Avatar asked Dec 03 '11 02:12

user1078494


People also ask

How do I center an image in a div horizontally?

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 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 center an object horizontally in a div?

Center Align Elements To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.

How do I hide the overflow of a picture?

To activate the overflow property enclose the image, within a div of a particular width and height, and set overflow:hidden . This will ensure that the base container will retain its structure, and any image overflow will be hidden behind the container.


2 Answers

If you know the width and height of the image beforehand (i.e. they're all the same) then you can use the old margin/position trick:

#myImage {
    height: the image's height;
    left: 50%;
    margin-left: -half the image's width;
    margin-top: -half the image's height;
    position: relative;
    top: 50%;
    width: the image's width;
}
like image 70
Ry- Avatar answered Sep 30 '22 10:09

Ry-


CSS:

 div {background:salmon; width:100%; height:200px; overflow:hidden;}
 img {left: 50%; margin-left:-1500px; position:relative;}

HTML:

 <div><img src="" /></div>

Demo

like image 41
bookcasey Avatar answered Sep 30 '22 11:09

bookcasey