There is a div of a given height, the width of the div in percent. An image is inserted into the div. With a screen resolution of more than 1024, the image is centered. At a resolution equal to or less than 1024, it is cut off from one edge, since block width becomes less than image width. How can you then horizontally center the image with js and trim it from both sides?

The option to resize the image is not suitable, because height div is fixed and the image should occupy it completely.

HTML:

<div class="box"> <img src="http://hashcode.ru/upfiles/logo.png"> </div> <div class="box"> <img src="http://hashcode.ru/upfiles/logo.png"> </div> <div class="box"> <img src="http://hashcode.ru/upfiles/logo.png"> </div> <div class="box"> <img src="http://hashcode.ru/upfiles/logo.png"> </div> 

CSS:

 .box { width: 21%; height: 70px; background: #222; float: left; text-align: center; margin: 20px 2%; overflow: hidden; } 
  • @ x01x, and is not it better to simply scale the image than to cut it? - Deonis
  • because only the width of the block changes when scaling there will be indents from the top and / or from the bottom. that doesn't quite fit. interests option precisely circumcision on the sides. - x01x

1 answer 1

@ x01x , you have not responded to my suggestion in the comments. So, I can offer this solution to your problem. Just keep in mind that the solution is not very cross-browser .

 .box { position: relative; display: inline-block; width: 21%; height: 70px; margin: 5px; text-align: center; border: 1px solid #999; overflow: hidden; } .box img{ position: absolute; -webkit-transform: translateX(-50%); -moz-transform: translateX(-50%); -ms-transform: translateX(-50%); transform: translateX(-50%); } 

UPD Option with JS

 var box = $('.box'), img = $('img', box), imgW = img.width(); $(window).resize(function(){ img.css({ marginLeft: (box.width() - imgW) / 2 }); }).resize(); 
  • Thanks for the solution. If I do not find a solution through js, then I will use it. - x01x
  • one
    @ x01x, strange ... Usually, first look for solutions without JS, but if you want this option, then you can build. Supplemented in the answer. - Deonis
  • thank. exactly what is needed! - x01x