CSS背景图片宽度100%高度自动

时间:2018-06-29 13:05:41

标签: javascript css

对于背景图像宽度为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>

4 个答案:

答案 0 :(得分:0)

**<div id="image">some content here</div>** Div正在根据其拥有的内容来确定高度。无法计算自动高度。背景将检查div的高度,并根据该高度显示图像。因此,设置height:100%或height:auto不会计算背景图像的高度。

您必须通过给div一些填充或设置其高度来自动排列高度。

答案 1 :(得分:0)

您可以使用基于百分比的填充值设置容器的高度。 这样,您的容器将保持背景图像的长宽比。 如果要在其中添加内容,还需要添加具有绝对位置的子元素。

#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>

答案 2 :(得分:0)

#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)

答案 3 :(得分:0)

您可以使用-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>

相关问题