css layering
2022-07-16
Here's how to layer elements above other elements!
Add position: relative; to the base layer:
<div class="base-layer">
some text here
</div>
position: relative;
Add a floaty layer with position: absolute;
You can specify whichever offset you like with top, bottom, left and right!
<div class="base-layer">
<div class="floaty-layer"></div>
some text here
</div>
position: relative;
position: absolute;
right: -20px;
bottom: 10px;
top: 10px;
10px below base layer's top line
top: -10px;
10px above base layer's top line
left: 10px;
10px to the right from base layer's left line
left: -10px;
10px to the left from base layer's left line
Note that you may encounter an issue where you cannot interact with the base layer due to floaty layer covering it.
For example, hovering cursor on the green element here is unlikely to change the cursor icon, despite the element having cursor: pointer;
position: relative;
position: absolute;
bottom: 0;
To fix this, you can add pointer-events: none; to the floaty layer.
The green text should now be interactable!
position: relative;
position: absolute;
bottom: 0;
pointer-events: none;
Last thing to note is that you can change the origin position of the floaty layer by using transform: translate(x, y);
circle 1 (top-left)
top: 0;
left: 0;
transform: translate(-50%, -50%);
The origin is in top-left corner, so we offset the floaty layer to the left by 50% of its width, and to the top by 50% of its height.
circle 2 (middle)
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
Similarly to the previous circle, the origin is in top-left corner, so we offset the floaty layer to the left by 50% of its width, and to the top by 50% of its height.
circle 3 (bottom-right)
bottom: 0;
right: 0;
transform: translate(50%, 50%);
This one is a bit different since we use bottom and right.
The origin is in bottom-right corner, so we offset the floaty layer to the right by 50% of its width, and to the bottom by 50% of its height.