Crop centered image inside div

旧巷老猫 提交于 2019-12-22 14:52:01

问题


I have a div containing an image (img) element, which extends for 100% width inside it. I would like to specify a maximum height for the div, and hide the parts of the image exceeding this height. But I also want to keep this image centered vertically inside the div to show only its central part.

For example, if browser width is 1200px and image aspect ratio is 4:3, image should display (1200x900)px. But if we want to crop height to 300px only and center vertically, image should position at -300px inside the div (and the div should hide 0-300 and 600-900 of the image height). Similar thoughts can be done for other widhts.

I'm pretty sure this can be easily done with javascript, but I would like to know if there is a way to do it with CSS too. Thanks in advance!


回答1:


My take on this: http://codepen.io/vsync/pen/DpmnK

HTML

<div class='box'>
  <img src="http://www.biztalk360.com/Events/BizTalk-Innovation-day-2014-Norway/images/banner.jpg">
</div>

SCSS

.box{
  // this is the image container distentions 
  width:100%;
  height:100px;

  // The magic
  > img{
    position:absolute;
    z-index:-1;
    top:50%;
    left:50%;
    width:100%;
    transform:translate(-50%, -50%); 
    &.max{ width:auto; height:100%; }
  }
}

javascript (this is only for responsiveness)

var photo     = document.images[0],
    container = document.querySelector('.box');

$(window).on('resize.coverPhoto', function(){
  requestAnimationFrame(checkRatio);
});

function checkRatio(){
  var state = photo.clientHeight <= container.clientHeight && 
              photo.clientWidth >= container.clientWidth;

  photo.classList[state ? 'add' : 'remove']('max');
}



回答2:


You may want to look at this question : Resizeing an oversized image using overflow:hidden and keep the aspect ratio

http://codepen.io/gcyrillus/pen/Grbxg

.grid_3 { width:260px; margin:0 20px; float:left;  text-align:center;
  overflow:hidden;background:rgba(255,255,255,0.02);}

.grid_3 a {
  display:block;  
  height:171px; border:solid 2px #FFFFFF;
  line-height:168px;
  overflow:hidden;
  margin-bottom:10px;
}
.max-img-border {  width:100%; margin:-100% 0;vertical-align:middle;
}

here is another pen , exploring this , vertical-align:middle and an image with virtually no height in the flux.http://codepen.io/gc-nomade/pen/DxCgv

Of course , image set in background center is easy if it has no meaning in your content.




回答3:


So you want the div to function as a viewing window for your image? This sounds like image sprites (a large pic of icons put together where each icon is displayed individually) but with a larger image:

http://www.w3schools.com/css/css_image_sprites.asp

If you provide a JSFiddle, I can give you something more specific.



来源:https://stackoverflow.com/questions/20432113/crop-centered-image-inside-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!