使用CSS仅选择图像的中间部分

时间:2015-04-21 12:13:43

标签: html css css3

我的图片有一些CSS:width:100%;

现在图像高约560px,但我希望只选择300px的图像,切断图像的顶部和底部而不会挤压它。

有可能这样做吗?

我看过crop,但你必须选择要执行此操作的部分,因此在尝试获得中间时它不会起作用。

Example of image cropping desired

6 个答案:

答案 0 :(得分:11)

试试这个。 这是使用" clip-path" CSS值。 这在@Sam Jacob的帖子中提到过。

<style>
.clip-me {  
  position: absolute;
  clip: rect(110px, 160px, 170px, 60px); 
  /* values describe a top/left point and bottom/right point */

  clip-path: inset(10px 20px 30px 40px); /* or "none" */
  /* values are from-top, from-right, from-bottom, from-left */

} 
</style>
<img class="clip-me" src="thing-to-be-clipped.png">

注意:此CSS属性在IE中工作。

答案 1 :(得分:4)

使用剪辑路径

img {
    position: absolute;
    clip: rect(0, 100px, 100px, 0); /* clip: shape(top, right, bottom, left);*/
}

编辑:正如评论中所提到的,该位置应该是绝对的或固定的,以使其起作用

如果您不想将位置设置为绝对位置或固定位置,请将要显示的图像设置为容器中的背景(td,div,span等),然后调整背景位置以获取精灵你想要的。

  

由于mozilla页面here表示使用剪辑不是网络标准,考虑使用剪辑路径或背景位置来实现此目的。

img{  

  /* deprecated version */
  position: absolute; /* absolute or fixed positioning required */
  clip: rect(110px, 160px, 170px, 60px); /* or "auto" */
  /* values descript a top/left point and bottom/right point */

  /* current version (doesn't require positioning) */
  clip-path: inset(10px 20px 30px 40px); /* or "none" */
  /* values are from-top, from-right, from-bottom, from-left */

} 

详细解释here

答案 2 :(得分:4)

对您的图片添加否定margin-top,家长需要overflow: hidden;

答案 3 :(得分:4)

您可以使用clip-path

/* values are from-top, from-right, from-bottom, from-left */
.clip {
    clip-path: polygon(5% 5%, 80% 5%, 80% 60%, 90% 60%, 5% 60%);
    -webkit-clip-path: polygon(5% 5%, 80% 5%, 80% 60%, 90% 60%, 5% 60%);
}

以下是一个例子:http://jsfiddle.net/q08g3948/1/

答案 4 :(得分:2)

您可以使用background-position代替(这与浏览器兼容)。

我知道你说过没有背景图片&#39; - 但这可以通过脚本动态添加,如果需要,也可以添加背景位置。

快速样本将是:

&#13;
&#13;
div{
  background:url(http://lorempixel.com/300/300);
  background-position:0 -100px;
  height:100px;
  width:300px;
  
  }
&#13;
<div></div>

<br/><br/>Original
<br/><br/>
<img src="http://lorempixel.com/300/300"/>
&#13;
&#13;
&#13;

答案 5 :(得分:2)

使用相对定位的div +绝对定位图像。使用top: -999px; bottom: -999px; margin-top: auto; margin-bottom: auto;垂直居中图像。绝对敏感。没有硬编码像素或百分比值。

&#13;
&#13;
.image-wrap {
  position: relative;
  overflow: hidden;
  /* fixed height */
  height: 300px;
  /* for demonstration */
  margin-top: 1em;
  margin-bottom: 1em;
  box-shadow: 0 0 .5em red;
}
.image-wrap img {
  position: absolute;
  /* fit horizontally */
  width: 100%;
  height: auto;
  /* center vertically */
  top: -1000px;
  bottom: -1000px;
  margin-top: auto;
  margin-bottom: auto;
}
&#13;
<div class="image-wrap">
  <img src="http://lorempixel.com/600/600/sports/4" width="600" height="600">
</div>
<div class="image-wrap">
  <img src="http://lorempixel.com/600/600/sports/5" width="600" height="600">
</div>
&#13;
&#13;
&#13;

相关问题