2016-07-28 74 views
-1

當我使用1920x1080圖片(或其他分辨率我嘗試過)的以下內容時,圖片的頂部會被截斷。有什麼辦法可以防止這種情況發生?100%寬的背景圖像頂部截圖

div.background { 
    background-image: url("/images/home.jpg"); 
    background-repeat: no-repeat; 
    position: absolute; 
    height: 100%; 
    width: 100%; 
    margin-top: 100px; 
    top: 0; 
    bottom: 0; 
    left: 0; 
    right: 0; 
    z-index: 0; 
    background-position: 50% 50%; 
    -webkit-background-size: cover; 
    -moz-background-size: cover; 
    -o-background-size: cover; 
    background-size: cover; 
} 

div.header { 
    background-color: red; 
    width:100%; 
    height: 100; 
    margin-top: 0px; 
    margin-right: 0px; 
    margin-left: 0px; 
    margin-bottom: 0px; 
    padding: 0px 0px 0px 0px; 

} 

body { 
    margin: 0px 0px 0px 0px; 
} 

<html> 
<head> 
<link rel="stylesheet" type="text/css" href="css/main2.css"> 
</head> 
<body> 
<div class="header"></div> 
<div class="background"></div> 
</body> 
</html> 

回答

0

將div.background的margin-top更改爲0px。這將從畫面

div.background { 
background-image: url("/images/home.jpg"); 
background-repeat: no-repeat; 
position: absolute; 
height: 100%; 
width: 100%; 
margin-top: 0px; 
top: 0; 
bottom: 0; 
left: 0; 
right: 0; 
z-index: 0; 
background-position: 50% 50%; 
-webkit-background-size: cover; 
-moz-background-size: cover; 
-o-background-size: cover; 
background-size: cover; 

}

+0

這涵蓋標題 – cente

1

這就是background-size: cover做,使得它讓你的背景圖片進行縮放,同時保持縱橫比,以支付其容器全部取出切斷。如果圖像的縱橫比與div不匹配,則會裁剪。

如果你能保證你的背景圖片將始終具有相同的縱橫比,你可以做這樣的事情:

div.background { 
    background-image: url("/images/home.jpg"); 
    background-repeat: no-repeat; 
    position: absolute; 

    /* these lines are the important bits */ 
    height: 0; 
    padding-bottom: 56.25%; 
    box-sizing: border-box; 

    width: 100%; 
    margin-top: 100px; 
    top: 0; 
    /* bottom: 0; */ 
    left: 0; 
    /* right: 0; */ 
    z-index: 0; 
    background-position: 50% 50%; 
    -webkit-background-size: cover; 
    -moz-background-size: cover; 
    -o-background-size: cover; 
    background-size: cover; 
} 

相對填充和利潤都基於width,不height。使用該特定百分比會導致div具有與圖像16:9匹配的寬高比。具有相同的寬高比意味着使用cover時不會發生削波。有關該主題,請參閱this answer

border-box使heightwidth以包括paddingborder尺寸但不margin大小,防止從margin實現所述div的尺寸。

+0

哇!複雜的迴應,我必須通過它,但這完全是它。謝謝 :-) – cente