Devilquest Devilquest - 24 days ago 10
CSS Question

Change div color with css checked selector

I have some problem when i try to change the color of a div using input tags. If the div is in the same section of the inputs it works perfect. But if i try to put the div in the footer, for example, stop working.

HTML:

<section>
<input id="select1" name="test" type="radio" checked />
<label for="select1">Red</label>
<input id="select2" name="test" type="radio" />
<label for="select2">Green</label>
<input id="select3" name="test" type="radio" />
<label for="select3">Blue</label>
</section>
<footer>
<div class="colorDiv"></div>
</footer>


CSS:

.colorDiv{
width:50px;
height:50px;
background-color:red;
}

#select2:checked ~ .colorDiv{
background-color:green;
}

#select3:checked ~ .colorDiv{
background-color:blue;
}


Here is an example: http://jsfiddle.net/cqscc48g

There is any way to achieve that?

Thanks

Answer

Css is a cascading renderer. So it follows the DOM element's structure. Therefore, you can only relate elements that are descendants or, at least following siblings.

You have two options:

1 - Adjust your HTML:
You don't even need to put the div inside the input's section. But at least, you'd have to let the inputs out of the section, to make a "nephew" selector. (of course this denomination does not exists ;) )

JsFiddle - Changin HTML

<input id="select1" name="test" type="radio" checked />
    <label for="select1">Red</label>
<input id="select2" name="test" type="radio" />
    <label for="select2">Green</label>
<input id="select3" name="test" type="radio" />
    <label for="select3">Blue</label>

<footer>
    <div class="colorDiv"></div>
</footer>

And then you can select:

#select2:checked ~ footer .colorDiv{
    background-color:green;
}

#select3:checked ~ footer .colorDiv{
    background-color:blue;
}

2 - Use a Javascript approach:

If you love your HTML structure so much, then you must go Javascript. You can make it a lot sharper, but just an example:

JsFiddle - Using Javascript

function ChangeColor(color) {
    var clrDiv = document.getElementsByClassName("colorDiv")[0];
    clrDiv.style.backgroundColor = color;
}

document.getElementById("select1").onclick = function() { ChangeColor(""); }
document.getElementById("select2").onclick = function() { ChangeColor("green"); }
document.getElementById("select3").onclick = function() { ChangeColor("blue"); }