I saw this question has similar threads but none that match my needs.
I’m creating a certain styled toggle button. I’m trying to have the "win" and "mac" containers chain to blue when they are selected. By default, "win" is the selected container so it’s blue, but if "mac" is selected, mac will have the background of blue and "win" will be white. Hope you get it?
.main-box {
border-style : solid;
border-color : #008aff;
border-width : 1px;
border-radius : 30px;
}
.flex-container {
display : flex;
flex-wrap : nowrap;
}
.active>.btn1 {
background-color : blue;
}
.flex-container>.btn {
width : 70px;
text-align : center;
line-height : 25px;
border-radius : 30px;
font-size : 20px;
}
<div class="main-box">
<div class="flex-container active">
<div class="btn1 btn">Win</div>
<div class="btn2 btn">Mac</div>
</div>
</div>
>Solution :
Use a checkbox and two <labels> associated to it by for attribute
Details are commented in example
.switch-box {
/* reduces the overall width to the width of the content */
width: max-content;
border: solid #008aff 1px;
border-radius: 30px;
}
#switch {
/* Checkbox is hidden */
display: none
}
.flex {
display: flex;
flex-wrap: nowrap;
}
.win {
background-color: blue;
}
#switch:checked + div .mac {
/*
When checkbox is checked, find the immediate <div> next to it then find
label.mac inside of it and assign "blue" to it's background.
*/
background-color: blue;
}
#switch:checked + div .win {
/*
When checkbox is checked, find the immediate <div> next to it then find
label.win inside of it and assign "white" to it's background.
*/
background-color: white;
}
.btn {
width: 70px;
border-radius: 30px;
font-size: 20px;
line-height: 25px;
text-align: center;
}
<div class="switch-box">
<input id='switch' type='checkbox'>
<div class="flex">
<label for='switch' class="win btn">Win</label>
<label for='switch' class="mac btn">Mac</label>
</div>
</div>