到目前为止我已经得到了这段代码(没有标题图像可见):
.wrap {
margin: 50px auto;
}
html,
body {
height: 100%;
}
body {
background-image: url('https://placebear.com/1000/800');
background-repeat: no-repeat;
background-position: center center;
background-size: cover;
background-attachment: fixed;
}
.header {
background-image: url('https://placebear.com/940/248');
background-repeat: no-repeat;
background-position: center center;
background-size: cover;
}
<div class="wrap">
<div class="row">
<div class="medium-12 columns header"></div>
</div>
</div>
如果您将标题图片的大小固定为 248 像素,您就可以看到它出现。带有可见标题图像的示例:
.wrap {
margin: 50px auto;
}
html,
body {
height: 100%;
}
body {
background-image: url('https://placebear.com/1000/800');
background-repeat: no-repeat;
background-position: center center;
background-size: cover;
background-attachment: fixed;
}
.header {
background-image: url('https://placebear.com/940/248');
background-repeat: no-repeat;
background-position: center center;
background-size: cover;
height: 248px;
border: 3px solid white;
}
<div class="wrap">
<div class="row">
<div class="medium-12 columns header"></div>
</div>
</div>
有没有办法让它在不使用固定高度的情况下出现?
就像使用经典的 img-tag 和 src- 和 alt-attribute 一样。然后从图像文件 self 中读取高度。
我想避免在那里设置固定高度,因为如果图像发生变化,那么一切都会变得错误。
最佳答案
我认为如果使用背景图像,您必须定义一个高度。可能最好使用 img 标签并将宽度设置为 100%,如下所示:
.wrap {
margin: 50px auto;
}
html,
body {
height: 100%;
}
body {
background-image: url('https://placebear.com/1000/800');
background-repeat: no-repeat;
background-position: center center;
background-size: cover;
background-attachment: fixed;
}
.header {
border: 3px solid white;
}
img {
width: 100%;
}
<div class="wrap">
<div class="row">
<div class="medium-12 columns header">
<img src="https://placebear.com/940/248" alt="Bear Image">
</div>
</div>
</div>
关于html - CSS:在没有内容和/或固定尺寸的情况下显示背景图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42996790/