This question is very similar to the one previously posted at: how-to-toggle-the-check-state-of-a-radio-input-element-on-click but the answer shared there only works when each input element is in its own separate div container; however, I need it to work for a specific HTML structure where all the radial inputs are instead at the same level directly inside a single parent div (I think this would probably be a more common structure for people anyway).
In the following example, I have three radio buttons acting as tabs for a tabbed section. The round button images are hidden using CSS, but the labels turn white when the radio input is: checked. The reason for this particular HTML structure is because the radio inputs must all be under the same parent at the same level as, but earlier than, the displayable content of the tabbed section in order for that hidden content to then be shown following the buttons, using a CSS selector like: #tab-1:checked ~ #tab-content-1{display:block}
.
So while the given CSS wasn't absolutely necessary to be provided for this example, it has been included to indicate a reason for keeping the HTML structure intact.
Here's the code:
/* The attributes in .tab-container are likely non-essential*/
.tab-container{
display:block;
margin:1rem;
}
.tab-label {
display:inline-block;
background: #eee;
border: 1px solid;
}
[name="tab-group-1"] {
display: none;
}
[name="tab-group-1"]:checked + .tab-label {
background: white;
border-bottom: 1px solid white;
}
#tab-1 ~ #tab-content-1, #tab-2 ~ #tab-content-2, #tab-3 ~ #tab-content-3 {
display:none;
}
#tab-1:checked ~ #tab-content-1, #tab-2:checked ~ #tab-content-2, #tab-3:checked ~ #tab-content-3 {
display:block;
align-self:bottom;
border:1px solid;
margin-top:-1px;
}
<div class="tab-container">
<input type="radio" id="tab-1" name="tab-group-1" checked><!--newline
--><label class="tab-label" for="tab-1">Tab One</label><!--newline
--><input type="radio" id="tab-2" name="tab-group-1"><!--newline
--><label class="tab-label" for="tab-2">Tab Two</label><!--newline
--><input type="radio" id="tab-3" name="tab-group-1"><!--newline
--><label class="tab-label" for="tab-3">Tab Three</label><!--newline
-->
<div class="content" id="tab-content-1">
stuff 1
</div>
<div class="content" id="tab-content-2">
stuff 2
</div>
<div class="content" id="tab-content-3">
stuff 3
</div>
</div>
Stuff at the end is not covered up...
Ultimately, it would be nice to be able to achieve a responsive tabbed container like this using only HTML and CSS (no JS), and it would be nice to be able to toggle the radio button off with CSS using something like: #tab-1:checked:focus{checked:false;}
but for the time being, I think some JS will have to be used just for this purpose of toggling a radio button off when it is toggled from a checked state.
Thanks for your help.