我的目标是拥有任何背景的div,然后使用伪元素来创建透明的白色叠加层,从而“减轻”div的背景.但是,“覆盖”必须在div的内容之下.所以,在下面的例子中:
- <div class="container">
- <div class="content">
- <h1>Hello,World</h1>
- </div>
- </div>
- .container {
- background-color: red;
- width: 500px;
- height: 500px;
- position: relative;
- }
- .content {
- background-color: blue;
- width: 250px;
- }
- .container::before {
- content:"";
- display: block;
- height: 100%;
- position: absolute;
- top: 0;
- left: 0;
- width: 100%;
- z-index: 1;
- background-color: rgba(255,255,.8);
- }
.content div不应该是“下面”的白色叠加层,也就是.container :: before.
我不喜欢在.content上使用z-index,但如果这是唯一的解决方案,我可以这样做.
最终目标:文字和蓝色不应覆盖红色.
解决方法
如果伪元素具有z-index,那么您需要定位.content元素并将z-index值添加到
establish a stacking context.
- .content {
- background-color: blue;
- width: 250px;
- position: relative;
- z-index: 1;
- }
你也可以从伪元素中删除z-index,然后只是放置.content元素.在这样做时,这些元素都不需要z-index.这个原因是因为:before伪元素本质上是一个先前的兄弟元素.因此,后续的.content元素位于顶部.
- .content {
- background-color: blue;
- width: 250px;
- position: relative;
- }
- .container::before {
- content:"";
- display: block;
- height: 100%;
- position: absolute;
- top: 0;
- left: 0;
- width: 100%;
- background-color: rgba(255,.8);
- }