Hello everyone I’m a beginner trying to get better at css. How can you target an element from another div in events like hover, checked, etc.
see example of what I mean below:
<div>
<input type="checkbox">
</div>
<div>
<button>example</button>
</div>
input:checked /how do I target button/{
background-color:#f0f0f0;
}
I learned that I can target sibling with ~ example
/if they were siblings/
input:checked ~ button {
background-color:#fefefe;
}
how can I do similar on elements from different parents.
2
Answers
To my knowledge this is only possible with a little JavaScript. Here is one way of doing it:
The
onchange
event handler is defined for each checkbox in the document. Whenever its status changes the event handler will start traversing the DOM structure up to the closest parent that is adiv
. It will then try to find the immediately following "ElementSibling" and select the first "button" element in it. For this element the background colour is then changed, according to the status of the changed checkbox.The script is still in a "quick and dirty" stage and does not yet provide suitable responses in case the
querySelector()
should not come up with a DOM element as a result.While it is possible to achieve this using JavaScript or obscure CSS tricks, it’s important to note that relying on relative position can be risky as it is unstable. Instead, consider adding an identifier to the button and changing its status/style in the input tag’s event handler.