2017-06-14 66 views
6

我正在嘗試調整背景圖片以適合div。我遇到的問題是我希望圖像適合div的高度並保持比例。例如,我有一個div,我不希望它進一步增加屏幕的寬度(以防止出現滾動條),而我想要使用的圖像是1024px X 400px。如果我嘗試適合圖像的高度,它會迫使寬度也適合,它會失去比例。我不在乎圖像的部分是否未顯示。事實上,那正是我想要做的。
我需要使用哪些標籤? HTML5和CSS調整圖像大小,保持比例,html?

回答

5

使用CSS background-size: cover;填補<div>,或background-size: auto 100%;如果你只是想企及的高度,並不在乎,如果雙方過度或不足流量:

html, 
 
body { 
 
    position: relative; 
 
    margin: 0; 
 
    padding: 0; 
 
    width: 100%; 
 
    height: 100%; 
 
} 
 

 
div { 
 
    background-image: url(https://placebear.com/1024/400.jpg); 
 
    display: inline-block; 
 
    background-repeat: no-repeat; 
 
    border: 1px solid black; 
 
} 
 

 
.cover { 
 
    background-size: cover; 
 
} 
 

 
.center { 
 
    background-position: center; 
 
} 
 

 
.height { 
 
    background-size: auto 100%; 
 
}
<h1>Unstyled</h1> 
 
<div style="width: 50px; height: 200px"></div> 
 
<div style="width: 200px; height: 50px"></div> 
 
<div style="width: 125px; height: 125px"></div> 
 

 
<h1>Un-centered</h1> 
 
<h2>Cover</h2> 
 
<div class="cover" style="width: 50px; height: 200px"></div> 
 
<div class="cover" style="width: 200px; height: 50px"></div> 
 
<div class="cover" style="width: 125px; height: 125px"></div> 
 

 
<h2>100% Height</h2> 
 
<div class="height" style="width: 50px; height: 200px"></div> 
 
<div class="height" style="width: 200px; height: 50px"></div> 
 
<div class="height" style="width: 125px; height: 125px"></div> 
 

 
<h1>Centered</h1> 
 
<h2>Cover</h2> 
 
<div class="cover center" style="width: 50px; height: 200px"></div> 
 
<div class="cover center" style="width: 200px; height: 50px"></div> 
 
<div class="cover center" style="width: 125px; height: 125px"></div> 
 

 
<h2>100% Height</h2> 
 
<div class="height center" style="width: 50px; height: 200px"></div> 
 
<div class="height center" style="width: 200px; height: 50px"></div> 
 
<div class="height center" style="width: 125px; height: 125px"></div>

另外,如果您想剪裁圖像以便中心始終是焦點而不是左上角,請使用background-position: center;

1

如果你可以降低你的比門檻一點,你也可以使用:

img { 
    width: 100vw; 
    height: 100vh; 
    max-width: 100%; 
    max-height: 100%; 
} 
相關問題