Ash*_*own 6 html css z-index css-position
所以我有这个标记,里面有<div class="mask"></div>将蓝色叠加层设置在图像顶部的标记。
如果我不做.container position:relative,标题文本就会隐藏在蓝色层后面......几乎就像它的用法是在模仿z-index
为什么会这样?
笔:https : //codepen.io/anon/pen/OBbbZB
body {
margin: 0;
font-family: arial;
}
section {
position: relative;
background: url(https://preview.webpixels.io/boomerang-v3.6.1/assets/images/backgrounds/slider/img-41.jpg)
no-repeat left center/cover;
height: 70vh;
display: flex;
justify-content: center;
}
.container {
position: relative;
width: 100%;
max-width: 1280px;
display: flex;
justify-content: center;
align-items: center;
color: white;
}
.mask {
position: absolute;
width: 100%;
height: 100%;
background: #3452ff;
opacity: 0.7;
}Run Code Online (Sandbox Code Playgroud)
<section>
<div class="mask"></div>
<div class="container">
<h1>Hello World</h1>
</div>
</section>Run Code Online (Sandbox Code Playgroud)
您需要参考规范,更准确地了解绘制顺序,以了解何时绘制每一层。
如果position:relative您的元素没有定位,将在步骤 (4) 中绘制:
- 对于按树顺序排列的所有流入、非定位、块级后代:如果元素是块、列表项或其他块等效项:
然后我们.mask在步骤(8)中绘制定位元素(包括)
- 所有定位、不透明度或变换后代,按树顺序分为以下类别
现在,当您添加时,position:relative您使容器也被定位,因此它也将落入步骤 (8) 中,正如那里所述,我们考虑树顺序,因为两者都没有z-index指定。所以.container在这种情况下,将在稍后绘制。
如果您更改元素的顺序(在蒙版之前制作容器),您会注意到这position:relative不会产生任何影响,因为在这两种情况下,绘制顺序将相同:
body {
margin: 0;
font-family: arial;
}
section {
position: relative;
background: url(https://preview.webpixels.io/boomerang-v3.6.1/assets/images/backgrounds/slider/img-41.jpg)
no-repeat left center/cover;
height: 70vh;
display: flex;
justify-content: center;
}
.container {
position: relative; /* you can remove this*/
width: 100%;
max-width: 1280px;
display: flex;
justify-content: center;
align-items: center;
color: white;
}
.mask {
position: absolute;
width: 100%;
height: 100%;
background: #3452ff;
opacity: 0.7;
}Run Code Online (Sandbox Code Playgroud)
<section>
<div class="container">
<h1>Hello World</h1>
</div>
<div class="mask"></div>
</section>Run Code Online (Sandbox Code Playgroud)
如果我们检查步骤(8),它也说不透明度或变换,这意味着如果你也改变容器的不透明度或添加变换,顺序也会改变。
body {
margin: 0;
font-family: arial;
}
section {
position: relative;
background: url(https://preview.webpixels.io/boomerang-v3.6.1/assets/images/backgrounds/slider/img-41.jpg)
no-repeat left center/cover;
height: 70vh;
display: flex;
justify-content: center;
}
.container {
transform:translate(0); /*added this*/
width: 100%;
max-width: 1280px;
display: flex;
justify-content: center;
align-items: center;
color: white;
}
.mask {
position: absolute;
width: 100%;
height: 100%;
background: #3452ff;
opacity: 0.7;
}Run Code Online (Sandbox Code Playgroud)
<section>
<div class="mask"></div>
<div class="container">
<h1>Hello World</h1>
</div>
</section>Run Code Online (Sandbox Code Playgroud)
值得注意的是,如果您添加z-index(负数或正数),您也会影响绘制顺序,在这种情况下,树顺序将不起作用。
- 堆叠上下文由具有负 z 索引(不包括 0)的定位后代以 z 索引顺序(最负的先)然后树顺序形成
....
- 由 z 索引大于或等于 1 的定位后代形成的堆叠上下文,按 z 索引顺序(最小的在前)然后是树顺序。
我们z-index在 (3) 处用负数绘制元素,在 (9) 处用正数绘制元素,在这些步骤之间,我们拥有所有z-index未涉及的情况,如最初所述。