Reputation: 642
Is this possible to have element with class .myelement always on top in my HTML structure?
<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
.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.
Here is full example: https://jsfiddle.net/wLzej01f/
EDIT What if all my classes will have to have position: relative? I forget to mention about it https://jsfiddle.net/wLzej01f/6/
Upvotes: 0
Views: 10813
Reputation: 61
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.asp
Upvotes: 1
Reputation: 25
.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**
Upvotes: -1
Reputation: 13534
Just add position:relative
to .myelement
:
.myelement {
z-index: 3;
background-color: yellow;
height: 500px;
width: 100px;
position: relative;
}
Upvotes: 0
Reputation: 1297
You forgot to add
position: absolute;
or
position: relative;
as you wish.
Upvotes: 0
Reputation: 3856
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>
Upvotes: 0
Reputation: 9614
The z-index
CSS property won't apply to static elements:
For a positioned box (that is, one with any position other than static), the z-index property specifies:
- The stack level of the box in the current stacking context.
- Whether the box establishes a local stacking context.
More about it here.
So, you need to add:
.myelement {
position: relative;
}
Updated JSFiddle.
Upvotes: 2