繁体   English   中英

如何裁剪不拉伸背景图像

[英]How to crop not stretch a background-image

我想对我的section元素使用width:100%height:40%的背景图像。

所以我用CSS3并使用了这个解决方案:

background-image: url(My_Local_Image);
background-repeat: no-repeat;
background-size: 100% 40%;
background-position: center top;

效果很好!

我现在的问题是我希望对背景图像进行裁剪以适合我指定的尺寸。 现在图像被拉伸以适合。

有没有可以实现这一目标的方法?

小提琴

不幸的是你不能做这样的事情

background-size: cover 40%;

因为你会失去100%

解决的办法是,制作一个单独的图像容器,然后在其后放置您(我想)文本的元素,只需设置background-size: cover; 对于图像容器,还设置width: 100%; height : 40%; 对于相同的。

但是你能做的是

现场演示

<section>
  <div class="sectionImage" id="first"></div>
  <div class="sectionContent">1</div>  
</section>

<section>
  <div class="sectionImage" id="second"></div>
  <div class="sectionContent">2</div>  
</section>

<section>
  <div class="sectionImage" id="third"></div>
  <div class="sectionContent">3</div>  
</section>

section{
  background:#444;
  position:relative;
  margin:10px auto;
  height:300px;
  width:800px;
  color:#fff;
}
.sectionImage{
  width: 100%;
  height:30%;
  background: transparent none no-repeat center center;
  background-size: cover;
}
.sectionContent{}

#first{
 background-image: url('1.jpg');   
}
#second{
  background-image: url(2.jpg);
}
#third{
  background-image: url(3.jpg);
}

如果我了解您要执行的操作,只需从背景尺寸中删除40%,图片就会以800x300px的尺寸填充div。

您必须将背景容器放入主容器中。 之后,您必须提供主容器的宽度和高度并进行溢出:隐藏。

然后,您可以使用主容器的宽度和高度来更改作物大小。 (您也可以使用width:40%; height:100%)

这是JSFidde

HTML:

<section id="first">
    <div id="bg"></div>
</section>

CSS:

#first{
  height:300px;
  width:200px;
  overflow:hidden;
}

#bg{
  background-image: url('https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQOhLJod_xPxdgo339zfIJipPzOUZg9BunbT-ftIgDMiu2HLi0o');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-position: center top;
  width:800px;
  height:300px;
}

使用内部div获得裁剪效果:

小提琴

CSS

#first{
    height:300px;
    width:800px;
}
#first div{
    width:100%;
    height:40%;
    background-image: url('https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQOhLJod_xPxdgo339zfIJipPzOUZg9BunbT-ftIgDMiu2HLi0o');
    background-repeat: no-repeat;
    background-size:100%;
    background-position: 50% 50%;
}

使用:before伪类

#first:before {
  content: '';
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 40%;
  background-image: url(image.jpg);
  background-repeat: no-repeat;
  background-position: center center;
}

这将为您提供许多CSS选项来处理较大/较小的图像,拉伸/裁剪等,而不会弄乱html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM