[英]CSS element always on top
Is this possible to have element with class .myelement always on top in my HTML structure?这是否可以让类 .myelement 的元素始终位于我的 HTML 结构的顶部?
<div class="zindex1">
<div class="myelement">
want THIS element always be on top
</div>
</div>
<div class="zindex2">
</div>
and with for example this CSS和例如这个CSS
.zindex1 {
z-index: 1;
background-color: blue;
height: 100px;
position: relative;
}
.zindex2 {
z-index: 2;
background-color: green;
height: 300px;
position: relative;
}
.myelement {
background-color: yellow;
height: 500px;
width: 100px;
position: relative;
}
NOTE: I can't change values of my z-indexes and HTML structure.注意:我无法更改 z-index 和 HTML 结构的值。
Here is full example: https://jsfiddle.net/wLzej01f/这是完整的示例: https : //jsfiddle.net/wLzej01f/
EDIT What if all my classes will have to have position: relative?编辑如果我所有的班级都必须有 position: relative 怎么办? I forget to mention about it https://jsfiddle.net/wLzej01f/6/
我忘了提到它https://jsfiddle.net/wLzej01f/6/
The z-index
CSS property won't apply to static elements: z-index
CSS 属性不适用于静态元素:
For a positioned box (that is, one with any position other than static ), the z-index property specifies:
对于定位框(即具有除 static 之外的任何位置的框), z-index 属性指定:
- The stack level of the box in the current stacking context.
当前堆叠上下文中框的堆叠级别。
- Whether the box establishes a local stacking context.
盒子是否建立了局部堆叠上下文。
So, you need to add:所以,你需要添加:
.myelement {
position: relative;
}
Position: relative职位:相对
.zindex1 { z-index: 1; background-color: blue; height: 100px; } .zindex2 { z-index: 2; background-color: green; height: 300px; } .myelement { z-index: 3; background-color: yellow; height: 500px; width: 100px; position: relative; }
<div class="zindex1"> <div class="myelement"> want THIS element always be on top </div> </div> <div class="zindex2"> </div>
You forgot to add你忘了添加
position: absolute;
or或
position: relative;
as you wish.如你所愿。
In case someone is trying to keep an element in a fixed position on the rest of the elements or does not know why one element is below another, keep in mind the sticky element.如果有人试图将一个元素保持在其他元素上的固定位置,或者不知道为什么一个元素低于另一个元素,请记住粘性元素。
https://www.w3schools.com/howto/howto_css_sticky_element.asphttps://www.w3schools.com/howto/howto_css_sticky_element.asp
.zindex1 {
z-index: 1;
background-color: blue;
height: 100px;
position: relative;
}
.zindex2 {
z-index: 0;
background-color: green;
height: 300px;
position: relative;
}
.myelement {
background-color: yellow;
height: 500px;
width: 100px;
position: absolute;
z-index: 2 !important;
}
**This code works**
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.