如何让单选按钮:checked而非:focus触发动画?选择器失效求助
Looks like you're trying to trigger that scale/border animation when a radio button is checked instead of just focused, but your selectors aren't hitting the mark—let's break this down and fix it.
First, your working :focus selector uses .item .radio-button:focus+.item-tile, which tells me your DOM structure has the radio button and .item-tile as adjacent siblings (right next to each other inside .item). That's good—so the + adjacent sibling selector should work for :checked too, if we rule out a few common pitfalls.
Common Fixes for :checked Not Triggering
Add a
nameattribute to your radio buttons
Radio buttons only toggle theircheckedstate when they're part of the same group (sharednamevalue). Without this, clicking a radio won't set itscheckedproperty, so your CSS selector will never match. Example:<div class="item"> <input type="radio" class="radio-button" name="tile-selection"> <div class="item-tile">Your Tile Content</div> </div> <div class="item"> <input type="radio" class="radio-button" name="tile-selection"> <div class="item-tile">Another Tile</div> </div>Match the specificity of your working
:focusselector
Your existing:focusrule works because it has the right specificity. Mirror that structure exactly for:checkedto avoid overrides. Update your CSS like this:/* Combine both states if you want focus and checked to trigger the animation */ .item .radio-button:focus+.item-tile, .item .radio-button:checked+.item-tile { border: 2px solid #079ad9; -webkit-transform: scale(1.1, 1.1); -ms-transform: scale(1.1, 1.1); transform: scale(1.1, 1.1); } /* Keep your existing base styles */ .item-wrap { display: flex; } .item-tile { display: -webkit-box; display: -ms-flexbox; display: flex; margin: 15px; background: white; -webkit-box-align: center; -ms-flex-align: center; align-items: center; padding: 1rem; /* Add padding to make the tile easily clickable */ cursor: pointer; }Ensure clicks on the tile trigger the radio button
If you've hidden the radio button (e.g., withopacity: 0orposition: absolute), wrap both elements in a<label>tag. This makes clicking anywhere on the tile activate the radio button, setting itscheckedstate:<label class="item"> <input type="radio" class="radio-button" name="tile-selection"> <div class="item-tile">Click Me to Check</div> </label>
Why Your Original Selectors Failed
.radio-button:checked ~ .item-tile: The~selector targets any subsequent sibling, not just the immediate next one. While this isn't broken, it's unnecessary for your adjacent structure and might have lower specificity than other styles.input[type=radio]:checked + .item-tile: This is valid, but your.radio-buttonclass selector has higher specificity than a bareinput[type=radio]rule. Using.item .radio-button:checked+.item-tilematches the specificity of your working:focusselector, so it will take effect.
内容的提问来源于stack exchange,提问作者Kyle Underhill

