繁体   English   中英

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

[英]Div with background-image overlayed by another div with background-image

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

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

这是我的小提琴

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不兼容

有任何想法吗?

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM