I have a fairly simple segmented controller-like radio button setup. When a radio button gets selected, that button gets a background color applied to it.
How can I get the background color to animate to the selected radio button in css?
Like this:
input {
display: none;
}
input:checked + .label {
background-color: yellowGreen;
}
<label>
<input type="radio" name="radioBtn" checked><span class="label">First Option</span>
</label>
<label>
<input type="radio" name="radioBtn"><span class="label">Second Opetion</span>
</label>
<label>
<input type="radio" name="radioBtn"><span class="label">Third Option</span>
</label>
Update
Because of the answer shortage, I'm now open to JavaScript/JQuery. Although if you do have a pure css solution, please post it.
Ok, Pure CSS, seems I came back late, still better than not coming back, JS Fiddle-Updated (1) (2)
Updated Code: added z-index
value to the container div#radios
(3)
body {
background: #EEE url('//www.dailyfreepsd.com/wp-content/uploads/2013/09/underwater-blurred-background.jpg');
background-size: cover;
}
#radios {
position: relative;
background-color: tomato;
z-index: 5;
width: 363px;
}
input {
display: none;
}
#bckgrnd,
.labels {
width: 120px;
height: 30px;
text-align: center;
display: inline-block;
padding-top: 10px;
margin-right: -3px;
z-index: 2;
cursor: pointer;
outline: 1px solid green;
}
#bckgrnd {
background-color: orange;
position: absolute;
left: 0;
top: 0;
z-index: -1;
}
#rad1:checked ~ #bckgrnd {
transform: translateX(0);
transition: transform 0.5s ease-in-out;
}
#rad2:checked ~ #bckgrnd {
transform: translateX(120px);
transition: transform 0.5s ease-in-out;
}
#rad3:checked ~ #bckgrnd {
transform: translateX(241px);
transition: transform 0.5s ease-in-out;
}
<div id="radios">
<input id="rad1" type="radio" name="radioBtn" checked>
<label class="labels" for="rad1">First Option</label>
<input id="rad2" type="radio" name="radioBtn">
<label class="labels" for="rad2">Second Option</label>
<input id="rad3" type="radio" name="radioBtn">
<label class="labels" for="rad3">Third Option</label>
<div id="bckgrnd"></div>
</div>
Edit:
(1) For smaller screens you can make a media query with a certain break point if below show these radios vertically, and instead of translateX()
use translateY()
.
(2) my below solution adds a div <div id="bckgrnd"></div>
as the last child of the container #radios
div, you can add by javascript/jquery instead, to do so you can add this jquery: JS Fiddle 2-Updated
$(document).ready(function(){
$('#radios').append('<div id="bckgrnd"></div>');
});
(3) The z-index:;
value was added just to ensure that the #bckgrnd
- which has z-index:-1
will not disappear behind the body
or whatever element contains the #radios
div. so now we can set a background image to the body and a background color to a container div without worrying about it.. Test JS Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With