Flexible use of checked pseudo-class selector to achieve single-select and multiple-select element effects
See the effect first
You can switch different options by clicking, and this example does not use js but is completely implemented with css.
:checked pseudo-class selector
The core of this effect is the :checked pseudo-class selector. This selector can match the element clicked by the user, which means that we can set the style for the element selected by the user separately.
Without further ado, let’s get straight to the code.
<divclass="cont"><!-- First create an input element. Although it will not be displayed, we need it to make the element selectable --><inputcheckedtype="radio"id="radio1"name="radio"/><!-- Then add a label after the input, and bind it to the input above through the for attribute, so that clicking this label is equivalent to clicking the input --><labelfor="radio1">Option 1</label><!-- Do the same for several options --><inputtype="radio"id="radio2"name="radio"/><labelfor="radio2">Option 2</label><inputtype="radio"id="radio3"name="radio"/><labelfor="radio3">Option 3</label><inputtype="radio"id="radio4"name="radio"/><labelfor="radio4">Option 4</label></div><style>.cont{display:flex;//Setaflexiblelayoutforthecontainersothatitsinternalelementsarearrangedhorizontally.line-height:120px;text-align:center;}label{//Thisisthestyleofthelabel.margin-right:10px;width:60px;height:120px;background:#ccc;border-radius:10px;transition-duration:.3s;}input{display:none;//Hidetheinputelement,itisjustatool.}input:checked+label{//Usecheckedtofindtheinputclickedbytheuser,andthenusethe+adjacentsiblingselectortoselectthelabelnexttothisinputandsetthestyleforit.transition-duration:.3s;width:120px;background:#99e6ff;color:#006080;}</style>
In the above code, we take advantage of the fact that <input type="radio"> can be clicked by users, and then bind the label element to it and place it behind it. In this way, not only can input be selected by clicking label, but also label can be selected by input using the adjacent sibling selector.
At this time, the input element as a tool can be hidden from the page, and we only need to design the style for the more operable label element.
The effect achieved by using this technique is far beyond your imagination.