[英]CSS Div Background Image Fixed Height 100% Width
我正在嘗試使用背景圖像設置一系列div,每個div都有自己的固定高度,並且拉伸以填充寬度,即使頂部/底部有被剪裁的溢出。 我只是不想要邊緣的白色空間。
目前,我有: http : //jsfiddle.net/ndKWN/
CSS
#main-container {
float:left;
width:100%;
margin:0;
padding:0;
text-align: center;
}
.chapter{
position: relative;
height: 1400px;
z-index: 1;
}
#chapter1{
background: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg) 50% 0 no-repeat fixed;
height:1200px;
}
#chapter2{
background: url(http://download.ultradownloads.com.br/wallpaper/94781_Papel-de-Parede-Homer-Simpson--94781_1680x1050.jpg) 50% 0 no-repeat fixed;
height:1200px;
}
請在此處查看我對類似問題的回答。
聽起來你想要一個背景圖像來保持它自己的寬高比,同時擴展到100%寬度並在頂部和底部被裁剪掉。 如果是這種情況,請執行以下操作:
.chapter {
position: relative;
height: 1200px;
z-index: 1;
}
#chapter1 {
background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
background-repeat: no-repeat;
background-size: 100% auto;
background-position: center top;
background-attachment: fixed;
}
jsfiddle: http : //jsfiddle.net/ndKWN/3/
這種方法的問題在於容器元素處於固定高度,因此如果屏幕足夠小,則可以在下方留出空間。
如果你想讓高度保持圖像的寬高比,你就必須做一些類似於我在上面鏈接到的答案的編輯中寫的東西。 將容器的height
設置為0,並將padding-bottom
設置為寬度的百分比:
.chapter {
position: relative;
height: 0;
padding-bottom: 75%;
z-index: 1;
}
#chapter1 {
background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
background-repeat: no-repeat;
background-size: 100% auto;
background-position: center top;
background-attachment: fixed;
}
jsfiddle: http : //jsfiddle.net/ndKWN/4/
如果每個圖像具有不同的寬高比,您還可以將padding-bottom
百分比放入每個#chapter
樣式中。 要使用不同的寬高比,請將原始圖像的高度除以其自身的寬度,然后乘以100以獲得百分比值。
你可以使用background-size: cover;
但問題是.chapter類不是動態的,你宣稱高度:1200px
所以最好使用背景:覆蓋並設置媒體查詢特定高度的流行分辨率。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.