簡體   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