这个问题在这里已有答案:
我需要某种优雅的背景图像宽度100%高度自动解决方案。它必须与它使用image src时的行为相同。我将在stackoverflow上使用另一个问题的示例,因为答案对我来说不起作用,也没有正常工作。
注意:我将把它放在具有自动宽度的css网格中,图像本身将具有边框。
如果有一个js解决方案,只要它有效,我不介意。
#image {
background-image: url(http://www.w3schools.com/css/trolltunga.jpg);
background-size: 100% auto;
background-position: center top;
background-repeat: no-repeat;
width: 100%;
height: auto;
}
<div id="image">some content here</div>
**<div id="image">some content here</div>**
Div根据其内容采取高度。它无法计算自动高度。背景将检查div的高度,并根据它将显示图像。因此设置高度:100%或高度:auto将无法计算出背景图像的高度。
您必须通过给div添加一些填充或设置其高度来自动排列高度。
您可以使用基于百分比的填充值设置容器高度。这样您的容器仍然是背景图像的纵横比。如果要在其中添加内容,还需要添加具有绝对定位的子元素。
#image {
background-image: url(http://www.w3schools.com/css/trolltunga.jpg);
background-size: 100% auto;
background-position: center top;
background-repeat: no-repeat;
width: 100%;
height: auto;
padding-top: 29.9%;
position: relative;
}
#image .child {
position: absolute;
top: 0;
left: 0;
}
<div id="image">
<div class="child">some content here</div>
</div>
#image {
background-image: url(http://www.w3schools.com/css/trolltunga.jpg);
background-size: cover;
background-repeat: no-repeat;
width: 100%;
height: 0;
padding-top: 30%;
}
<div id="image">some content here</div>
你只需要知道图像比例
for ex the image ratio was 1000x300
to get the padding-top (percentage) required use formula (300/1000 * 100)
您可以使用-webkit-fill-available。它会给出预期的结果。但它仅适用于Chrome和Safari
#image {
background-image: url(http://www.w3schools.com/css/trolltunga.jpg);
background-size: 100% auto;
background-position: center top;
background-repeat: no-repeat;
width: 100%;
height: -webkit-fill-available;
}
<div id="image">some content here</div>