Center image horizontally inside overflow: hidden div

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

+6
source share
3 answers

If you know the width and height of the image in advance (i.e. all are the same), you can use the old margin / position trick:

 #myImage { height: the image height; left: 50%; margin-left: -half the image width; margin-top: -half the image height; position: relative; top: 50%; width: the image width; } 
+10
source

CSS

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

HTML:

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

Demo

+1
source

Say myImg.jpg is 100x100px:

 <div style="overflow:hidden; width:100%;"> <img src="myImg.jpg" style="left: 50%; top:50%; position:relative; margin:-50px 0 0 -50px; width:100px; height:100px;" /> </div> 
0
source

Source: https://habr.com/ru/post/902979/


All Articles