Position relative? Isolation isolate!
So I use position: absolute;
quite alot; For example on sections
. Consider my websites have the following setup:
<main>
<section class="section">
<div class="section-inner">
<h2>Content</h2>
<p>lorem short</p>
</div>
</section>
</main>
Then I always have section modifiers that allow the website editor to set background colors, like so:
.section {
position: relative;
&::before {
content: "";
position: absolute;
inset: 0;
background: var(--object-background-color, transparent);
opacity: var(--object-background-opacity, 1);
}
.section-inner {
container-type: inline-size;
container-name: section-inner;
}
&:target {
animation: highlight 1s ease-in-out 0.5s;
}
}
/* Animation for highlighting */
@keyframes highlight {
0% {
background-color: #fff; /* Start with the default background color */
}
50% {
background-color: #ffe58a; /* Light yellow color */
}
100% {
background-color: #fff; /* End with the default background color */
}
}
Normally I have a helper class that sets the --object-background-color
but for this example I use it inline, see the following real html:
Section inner content
This is some text with a hyper link to homepage
However you cannot click it because it is inside a section-inner container. And the ::before.
Even though you might expect the ::before element to appear before .section-inner, it actually appears on top. This happens because the ::before element, when given position: absolute, creates its own stacking context. While .section-inner does not. As a result, .section-inner ends up being below it in the stacking order.
Possible fix
Comes to the rescue isolation: isolate
!
.section-inner {
container-type: inline-size;
container-name: section-inner;
/* 🆕 */
isolation: isolate;
}
This will pop it out of the stacking order! You could do position: relative; z-index: 1;
, but this would create a new stacking context and if you have position absolute items inside .section-inner
they would now anchor to this div and not the .section
.
Section inner content
This is some text with a hyper link to homepage
However you cannot click it because it is inside a section-inner container. And the ::before.
I've learned about this from this nice video from Kevin Powell.
I'll will use this when needed from now on, cheerio!
Sources:
- https://youtu.be/cNS0qWHEq58?si=TpuMiVSrSYxFFtHf
- https://developer.mozilla.org/en-US/docs/Web/CSS/isolation
- Previous: Table style starting point