html - CSS:在没有内容和/或固定尺寸的情况下显示背景图像?

标签 html image css

到目前为止我已经得到了这段代码(没有标题图像可见):

.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/

相关文章:

javascript - 缓存不能正常工作

image - 使用golang获取图片大小

c++ - 使用 "argv"传递图像文件C++

html - Bootstrap 3 两列全高

jquery - 使用jquery `<li><span>`时如何下推 `.slidedown()`

php - 302 图像在浏览器中重定向速度较慢

javascript - 在弹出窗口以外的任何地方单击时关闭弹出窗口?

c# - 路径问题 C#.net Image

html - 基础表格 - 验证错误 "End div tag seen, but open elements"

jquery - 点击后CSS悬停状态变为非事件状态