I am in the process of creating a tab system using only CSS with the help of the :target
and :checked
pseudo classes. However, I have encountered an issue where an anchor inside the label is not triggering the :checked
.
When clicking on the anchor, the :checked
does not trigger because the click occurs within the <a>
tag. The anchor is nested inside a <label>
that should be triggering the radio button. Clicking on the border of the tab triggers the :checked
but not the anchor, making it impossible to trigger the :target
.
Below is my code which provides a clearer understanding:
a {
text-decoration: none;
}
.tabs {
position: relative;
}
input {
display: none;
}
.tabs .tab label {
text-decoration: none;
border: 1px solid black;
padding: 2px;
display: inline-block;
top: 2px;
position: relative;
cursor: pointer;
}
.tabs .tab input:checked + label {
background-color: white;
border-bottom: 0;
padding: 4px 2px;
top: 1px;
}
.contents {
border: 1px solid black;
background-color: white;
}
.contents .content {
display: none;
padding: 20px;
}
.contents .content:target {
display: block;
}
<div class="tabs">
<span class="tab">
<input type="radio" name="ch" id="check1">
<label for="check1">
<a href="#tab1">Tab 1</a>
</label>
</span>
<span class="tab">
<input type="radio" name="ch" id="check2">
<label for="check2">
<a href="#tab2">Tab 2</a>
</label>
</span>
<span class="tab">
<input type="radio" name="ch" id="check3">
<label for="check3">
<a href="#tab3">Tab 3</a>
</label>
</span>
</div>
<div class="contents">
<div class="content" id="tab1">Content 1</div>
<div class="content" id="tab2"><strong>Content 2</strong></div>
<div class="content" id="tab3"><em>Content 3</em></div>
</div>
Is there a way to effectively combine the :checked
and :target
pseudo classes to create a fully functional tab system using just CSS?
Thank you.
EDIT
Here is a version of the snippet without the anchor. As expected, the :target
will not be triggered:
a {
text-decoration: none;
}
.tabs {
position: relative;
}
input {
display: none;
}
.tabs .tab label {
text-decoration: none;
border: 1px solid black;
padding: 2px;
display: inline-block;
top: 2px;
position: relative;
cursor: pointer;
}
.tabs .tab input:checked + label {
background-color: white;
border-bottom: 0;
padding: 4px 2px;
top: 1px;
}
.contents {
border: 1px solid black;
background-color: white;
}
.contents .content {
display: none;
padding: 20px;
}
.contents .content:target {
display: block;
}
<div class="tabs">
<span class="tab">
<input type="radio" name="ch" id="check1">
<label for="check1">
Tab 1
</label>
</span>
<span class="tab">
<input type="radio" name="ch" id="check2">
<label for="check2">
Tab 2
</label>
</span>
<span class="tab">
<input type="radio" name="ch" id="check3">
<label for="check3">
Tab 3
</label>
</span>
</div>
<div class="contents">
<div class="content" id="tab1">Content 1</div>
<div class="content" id="tab2"><strong>Content 2</strong></div>
<div class="content" id="tab3"><em>Content 3</em></div>
</div>