父元素的背景图像是否可能优先于子元素的背景颜色?

时间:2019-06-14 00:29:09

标签: css background-image background-color

这是一个简化的示例:

<style>
.container {
    background-image: url('https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=format%2Ccompress&cs=tinysrgb&dpr=1&w=500');
    height: 300px;
    width: 500px;
}

.child {
    // This takes precedence over background-image of the parent .container
    background-color: red;
    width: 100px;
    color: white;
}
</style>

<div class="container">
  <div class="child">
    hello
  </div>
</div>


https://codepen.io/anon/pen/pXjWOj

子元素的红色背景颜色优先于背景图像。虽然通常这是期望的行为,但我有一个用例,其中我需要父级的背景图像优先。

https://codepen.io/anon/pen/VJLQzd

在此示例中,我使用background-image在父元素上有阴影,该阴影告诉用户还有更多元素可以滚动。但是,子元素的background-color优先于父元素的background-image阴影。

1 个答案:

答案 0 :(得分:0)

您可以将Display元素中的z-index设置为-1,从而在视觉上获得所需的效果。但这可能会影响您希望用户与元素进行交互的方式……希望能有所帮助。


演示

.el
#container {
  display: flex;
  padding: 50px;
  border: 1px solid grey;
  width: 320px;
  overflow: scroll;
  scroll-snap-type: x mandatory;
  margin: 0 auto;
  
  
  	  background-image:
    /* Shadows */ 
    linear-gradient(to right, white, white),
    linear-gradient(to right, white, white),
/* Shadow covers */ 
    linear-gradient(to right, rgba(0,0,0,.15), rgba(255,255,255,0)),
    linear-gradient(to left, rgba(0,0,0,.15), rgba(255,255,255,0));   

  background-position: left center, right center, left center, right center;
	background-repeat: no-repeat;
	background-size: 10px 100%, 10px 100%, 5px 100%, 5px 100%;
  background-attachment: local, local, scroll, scroll;
}

.el {
  z-index: -1;
  text-align: center;
  padding: 10px;
  margin: 5px;
  border: 1px solid grey;
  scroll-snap-align: center;
  min-width: 300px;
  background-color: aliceblue;
  background
}

html {
  background: #FFF;
}