【问题标题】:CSS: Make a background-image appear without having content and/or fixed sizes?CSS:在没有内容和/或固定大小的情况下显示背景图像?
【发布时间】:2017-08-17 05:33:57
【问题描述】:

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

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

如果你给 header-image 一个 248px 的固定大小,你可以看到它出现。带有可见标题图像的示例:

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

有没有办法让它在不使用固定高度的情况下出现?

就像使用带有 src- 和 alt-attribute 的经典 img-tag 时一样。然后从图像文件中读取高度。

我想避免那里的固定高度,因为如果图像发生变化,那就完全错了。

【问题讨论】:

标签: html image css


【解决方案1】:

如果使用背景图像,我认为你必须定义一个高度。使用 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>

【讨论】:

  • 是的。我猜你是对的。来自萨尔的问候。
猜你喜欢
  • 2015-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-21
  • 2016-01-28
  • 2014-04-29
  • 1970-01-01
相关资源
最近更新 更多