裁剪中心图像在div [英] Crop centered image inside div

查看:212
本文介绍了裁剪中心图像在div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div包含一个图像(img)元素,它在其内部延伸100%的宽度。我想为div指定最大高度,并隐藏超过此高度的图像部分。但我也想保持这个图像在div的垂直内部,只显示它的中心部分。

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.

例如,如果浏览器宽度为1200像素,图像宽高比为4:3,图片应显示(1200x900)像素。但是如果我们要将高度裁剪为300px,垂直居中,图片应该位于div内部的-300像素(div应该隐藏图片高度的0-300和600-900)。类似的想法可以为其他widhts做。

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.

我确定这可以很容易地用javascript,但我想知道如果有一种方法它与CSS。提前感谢!

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!

推荐答案

我的意思是:http://codepen.io/vsync/pen/DpmnK

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



SCSS



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(这只是为了响应) h2>

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');
}

这篇关于裁剪中心图像在div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆