所以我有一个div,它显示一个大标题,两边有两行,填充了其余的宽度。
然而,现在我需要在这后面画一些文本,因为我用背景色画标题栏,所以它们被画在文本后面。
我怎么能把它画成从后到前显示的组件是[bg背景色]->[bg:bfore]->[标题:背景色之前/之后]->[标题]?
这是我的代码:
#bg
{
width: 100%;
height: 100%;
background-color: silver;
z-index: -1;
}
#bg:before
{
content: 'Background';
position: absolute;
font-size: 3em;
color: white;
user-select: none;
}
#bg *
{
z-index: 0;
}
.title
{
display: flex;
flex-direction: row;
align-items: center;
}
.title:after, .title:before
{
content: '';
width: 50%;
background-color: black;
height: 0.2em;
margin-left: 20px;
margin-right: 20px;
}
.section_titre h1
{
font-size: 1em;
margin: 0px;
}
<div id="bg">
<div class="title">
<h1>Example</h1>
</div>
</div>
z-indexCSS属性设置已定位元素及其子项或flex项的z顺序。z索引较大的重叠元素覆盖了z索引较小的元素
我们使用z索引
背靠背
- [bg背景色]->[bg:之前]->[标题:背景色之前/之后]->[标题]
因此,
首先将z索引(1(添加到bg背景色
#bg{
z-index: 1;
position:relative;// z-index work with other than static position
}
在这里,我使用了position:relative;
。为什么?使用z索引中的定位
z索引对该元素没有影响,因为它不是定位元素尝试将其position属性设置为static以外的属性。
然后将z索引(2(添加到bg:在之前
#bg:before {z-index:2;}
然后将z索引(3(添加到标题:背景色之前/之后
.title:after, .title:before {z-index:3;}
最后z索引(4(到标题
.title{z-index:4;position:relative;}
工作演示
#bg{
width: 100%;
height: 100%;
background-color: silver;
z-index: 1;
position:relative;
}
#bg:before{
content: 'Background';
position: absolute;
font-size: 3em;
color: white;
user-select: none;
z-index:2;
}
.title{
display: flex;
flex-direction: row;
align-items: center;
z-index:4;
position:relative;
}
.title:after, .title:before{
content: '';
width: 50%;
background-color: black;
height: 0.2em;
margin-left: 20px;
margin-right: 20px;
z-index:3;
}
.section_titre h1{
font-size: 1em;
margin: 0px;
}
<div id="bg">
<div class="title">
<h1>Example</h1>
</div>
</div>