我正在尝试使元素位置的边距为负-一个元素应该覆盖前一个元素。但这有点复杂-负边距应该只有#content的子div。请参见下面的示例。我需要有红色元素,而不是红色元素中的黄色元素和灰色元素应该具有负的页边距并覆盖红色元素的底部。
我已经尝试过相对和绝对位置,更改z-index,但是这些都不适合我。
#sectionTitle {
height: 150px;
text-align: center;
margin: 0 auto;
width: 100%;
position: relative;
z-index: 1;
background: red;
}
#content {
background: yellow;
position: relative;
width: 100%;
height: auto;
min-height: 300px;
overflow: auto;
z-index: 20;
}
#content .block {
position: relative;
background: #eee;
width: 90%;
top: -50px;
margin: 0 auto 0 auto;
box-sizing: border-box;
height: auto;
min-height: 400px;
z-index: 30;
}
<div id="sectionTitle">
...some text...
</div>
<div id="content">
<div class="block">
...element which should cover bottom of #sectionTitle element
</div>
</div>
现在,当我检查元素时,.block
变为#sectionTitle
50px,但是它不可见,因为sectionTitle元素覆盖了它。
答案 0 :(得分:0)
只需删除z-index
(以避免创建堆栈上下文 1 )和overlow:auto
(避免创建块格式设置上下文 2 ,来自#content
的div:
#sectionTitle {
height: 150px;
text-align: center;
margin: 0 auto;
width: 100%;
position: relative;
z-index: 1;
background: red;
}
#content {
background: yellow;
width: 100%;
height: auto;
min-height: 300px;
}
#content .block {
position: relative;
background: #eee;
width: 90%;
top: -50px;
margin: 0 auto 0 auto;
box-sizing: border-box;
height: auto;
min-height: 400px;
z-index: 30;
}
<div id="sectionTitle">
...some text...
</div>
<div id="content">
<div class="block">
...element which should cover bottom of #sectionTitle element
</div>
</div>
1 Why can't an element with a z-index value cover its child?
2 What formatting context applies to elements that don't create their own?