具有背景图像的div被具有背景图像的另一个div覆盖

时间:2018-08-07 07:53:22

标签: html css html5 css3 css-selectors

我正在尝试使用z-index属性将2个包含背景图像的div元素放置在彼此的顶部,但是我正在努力使这项工作生效。

理想情况下,随着屏幕越来越小,我希望div banner-image元素在div banner-image-overlay元素下方滑动。

Here is my fiddle

HTML:

<div id="banner-container">
  <div class="banner-image-overlay"></div>
  <div class="banner-image"></div>
  <div class="banner-text">
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
    </p>
    <p>
      Lorem ipsum dolor sit amet
    </p>
    <button class="banner-button" onclick="location.href='http://www.example.com'">
    Button
    </button>
  </div>
</div>

CSS:

#banner-container {
  width: 100%;
  position:relative;
}    
.banner-image {
  height: 375px;  
  background-image: url('http://via.placeholder.com/502x375');
  background-repeat: no-repeat;
  background-position: left top;
}    
.banner-image-overlay {
  height: 375px;  
  background-image: url('http://via.placeholder.com/399x375');
  background-repeat: no-repeat;
  background-position: right top;
  z-index: 99;
}    
.banner-text {
  max-width: 240px;
  font-family: 'Helvetica Neue Light', arial;
  color: #fff;
  font-size: 1.6em;
  float: right;
  position: absolute;
  right: 35px;
  top: 15px;
  z-index: 199;
}
.banner-button {
  max-width: 240px;
  font-size: 0.9em;
  background-color: #fff;
  border: none;
  border-radius: 4px;
  font-family: 'Helvetica Neue Light', arial;
  color: #000;
  text-decoration: none;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  margin: 4px 2px;
  cursor: pointer;
 }

我只是不知道如何将它们放置在彼此的顶部。

我已经使用普通的img标签,然后使用position: absolute属性,但是似乎不适用于background-image: url

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

position: absolute的工作需要有z-index

通过使用弹性框,我有一个更好的解决方案:

.banner{position:relative; display:flex;width:375px;height:500px; background:left top url(https://picsum.photos/300/300) no-repeat}
.banner-bg{flex:1 1;background:right top url(https://picsum.photos/200/280) no-repeat}
.banner-title{font-size:30px}
<div class="banner">
   <div class="banner-bg">
       <div style="position:absolute;width:150px;right:10px;top:100px">
         <div class="banner-title">HERE IS LONG TEXT...</div>
         <button>GET IN TOUCH</button>
       </div>
   </div>
</div>

如您所见,右侧背景位于左侧背景上方。

答案 1 :(得分:0)

默认情况下,

div元素相对放置,这意味着它们将彼此相邻。 z-index不会更改其位置。如果要堆叠它们,则必须更改它们的位置。绝对将其中之一放置在left和top设置为0的情况下,即可堆叠它们。 将position:absolute添加到.banner-image-overlay。

相关问题