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.
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.
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 ).
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.
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.
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;
}
CSS:
div {background:salmon; width:100%; height:200px; overflow:hidden;}
img {left: 50%; margin-left:-1500px; position:relative;}
HTML:
<div><img src="" /></div>
Demo
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