Here is a unique solution that I discovered, different from any other solutions provided so far. This method may only work on modern browsers (I have tested it on a Chromium browser from late 2023), but the following CSS code worked well for me with just a minor HTML tweak:
<style type="text/css">
.tab {
display: none;
}
.tab:target, :not(:has(.tab:target)) .tab.default {
display: block;
}
</style>
In addition to this, I found another even better solution after posting this, which involves changing the ul
element with the id updates-list
to a div
, or wrapping it in a div
with a class
attribute containing "tab":
.tab {
display: none;
}
.tab:target {
display: block;
}
.tab_container {
&:not(:has(.tab:target)) {
& .tab:first-of-type {
display: block;
}
}
}
(Returning to discussing the first solution now.)
To implement this in the HTML, I simply added "default" to the class list of the #updates-list
ul tag:
(Note: you could still use ID selection instead of adding a new class, but I personally found this approach cleaner. I also included some text within #updates-map
for testing purposes.)
<div class="tab_container">
<ul class="tabs">
<li><a href="#updates-list">List</a></li>
<li><a href="#updates-map">Map</a></li>
</ul>
<ul class="tab list default" id="updates-list"gt;
Hello!
</ul>
<div class="tab map" id="updates-map"gt;
[Placeholder for map]
</div>
</div>
Explanation:
The second selector in the CSS code snippet,
:not(:has(.tab:target)) .tab.default
, identifies a scenario where there is no
.tab
item with the
:target
attribute. In such cases, the style rule
display: block;
is applied to any
.tab
element with the additional class of
.default
.
This method has several advantages:
- It does not rely on a specific order, unlike some other approaches;
- Multiple tabs could potentially have the default attribute, resulting in multiple items being displayed if no specific target is selected.
On a side note, credit goes to Amy Kapernick for inspiring me to explore this JavaScript-free solution through her talk and demo site showcasing similar techniques without JavaScript.