所以我有一个div,该div显示一个大标题,其两侧有两行填充其余宽度。
但是,现在我需要在此后面绘制一些文本,并且因为我要用背景色绘制标题栏,所以它们被绘制在文本后面。
如何以这样的方式绘制它,即从后到前显示的组件是[bg background-color]-> [bg:before]-> [title:before / after background-color]-> [title ]?
这是我的代码:
#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>
答案 0 :(得分:2)
z-index CSS属性设置定位元素及其后代或flex项的z顺序。 Z-index较大的重叠元素将覆盖较小的元素。
从前到后的
所以
首先将z-index(1)添加到 bg背景颜色
#bg{
z-index: 1;
position:relative;// z-index work with other than static position
}
position:relative;
。为什么?在z-index中使用定位?z-index 对此元素无效,因为它不是定位元素。尝试将其position属性设置为 static 以外的其他值
然后将z-index(2)添加到 bg:before
#bg:before {z-index:2;}
然后将z-index(3)添加到 title:背景颜色之前/之后
.title:after, .title:before {z-index:3;}
最后将z-index(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>