我正在尝试在两个嵌套元素之间渲染一个元素。最好用一个例子来说明:
#parent {
position: fixed;
top: 0;
left: 0;
width: 200px;
height: 200px;
z-index: 0;
background-color: red;
}
#child {
position: fixed;
top: 50px;
left: 50px;
width: 100px;
height: 100px;
z-index: 2;
background-color: blue;
}
#other {
position: fixed;
top: 25px;
left: 25px;
width: 50px;
height: 50px;
z-index: 1;
background-color: green;
}
<div id="parent">
<div id="child"></div>
</div>
<!-- I want to have this element in between the "parent" and "child". -->
<div id="other"></div>
在这种情况下,我希望在红色父级(“ #parent”)和蓝色子级(“ #child”)元素之间(z深度方向)呈现绿色(“ #other”)元素。换句话说,我希望蓝色元素位于最上方。
根据我的理解,由于元素是嵌套的,因此无法使用CSS的z深度(就像我尝试过的那样),但是我似乎无法找出另一种方式。
如果可能的话,我想保持HTML的原样,并完全在CSS中完成。
谢谢!
答案 0 :(得分:0)
刚刚从position:fixed
中删除了#parent
。您可以为position: static;
添加#parent
。
答案 1 :(得分:0)
您的问题仍然不清楚,因此,我将推荐现有的解决方案。
首先,如果您不想触摸html,则可以使用js移动元素。请参阅this链接。
第二,这种功能与元素wrapping
密切相关。这也出现在jquery中。
第三,您可能需要检出:before
和:after
伪元素。检出this链接。
答案 2 :(得分:0)
嵌套在z-index
中起着重要作用。如果#other
元素位于#parent
元素的顶部,则{{ 1}}绝对不能高于#child
元素。这是#parent
的重要规则。
在这种情况下,您可以通过以下方式更改HTML代码以创建所需的形状。
#other
z-index
#parent {
position: fixed;
top: 0;
left: 0;
width: 200px;
height: 200px;
z-index: 0;
background-color: red;
}
#child {
position: fixed;
top: 50px;
left: 50px;
width: 100px;
height: 100px;
z-index: 2;
background-color: blue;
}
#other {
position: fixed;
top: 25px;
left: 25px;
width: 50px;
height: 50px;
z-index: 1;
background-color: green;
}
<div id="parent">
<div id="child"></div>
<div id="other"></div>
</div>
编辑:要保留HTML,无需为#parent {
position: fixed;
top: 0;
left: 0;
width: 200px;
height: 200px;
z-index: 0;
background-color: red;
}
#child {
position: fixed;
top: 50px;
left: 50px;
width: 100px;
height: 100px;
z-index: 2;
background-color: blue;
}
#other {
position: fixed;
top: 25px;
left: 25px;
width: 50px;
height: 50px;
z-index: 1;
background-color: green;
}
使用任何<div id="parent"></div>
<div id="child"></div>
<div id="other"></div>
样式,也无需删除其中的position
值。
#parent
top|left|z-index