背景图片全宽和全高

Background image full width and height

我正在为网站设置横幅。横幅由一张图片和上面的一些文字组成,代码如下:

<div class="banner_div">
<style>
    .banner_div{
        background-image: url(/images/banner.jpg);
        width: 100%;
        height: 100%;
        background-size: contain;
    }
</style>
<p class="banner_text">Line 1</br>Line 2</p>
</div>

我需要的是图像覆盖整个屏幕宽度(即使屏幕比图像宽,在这种情况下图像应该拉伸)和 div 的高度相应地缩放,以便完全显示图像。我怎样才能做到这一点?我尝试了 background-size 中的每一个 属性,但都没有用...

编辑:当前的问题是高度与文本之一成比例

尝试以下解决方案:

body, html {
  margin:0;
  padding:0;
}
.banner_div {
  background-image: url(http://placehold.it/100x100);
  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background-size:cover;
  background-position: center;
}
<div class="banner_div">
  <p class="banner_text">Line 1</br>Line 2</p>
</div>

首先使用 16:9 图片以获得更好的效果:

然后使用img标签本身,

在不考虑纵横比的情况下缩放图像对于横幅来说可能看起来不太好,因此我们使用 width:100%height:auto 来保持横幅比例。 大多数屏幕使用 16:9 比例,所以如果你有 16:9 图像

应该会很好

body,
html {
  margin: 0px;
  padding: 0px;
  height: 100%;
}

.banner{
  display:block;
  }

.banner img {
  width: 100%;
  height: auto;
  position: relative;
}
.banner p {
  float:left;
  position:absolute;
  top:0px;
}
<div class="banner">

  <img src="https://upload.wikimedia.org/wikipedia/commons/7/7c/Aspect_ratio_16_9_example.jpg" />
  <p>Some text here</p>
</div>

Some random text to show other elements wont overlap the banner

对于你的问题,我有更好的解决方案。

问题是因为您没有给出 HTML,BODY 的高度。 如果你给了高度这个问题就解决了,不需要添加位置元素,以后会出现一些对齐问题

解决方案

HTML

<div class="banner_div">
<p class="banner_text">Line 1</br>Line 2</p>
</div>

CSS

    html,body{
      height:100%;
      margin:0;
      padding:0;
    }
    .banner_div{
        background-image: url(http://placehold.it/100x100);
        background-size: cover;
         background-position: center;
        width:100%;
        height:100%;
    }
    .banner_text{
      margin:0;
      padding:20px;
    }
<div class="banner_div">
<p class="banner_text">Line 1</br>Line 2</p>
</div>

这个 css 代码与我一起工作:

background-size: 100% 100%;