I have a situation where a third party software provides an html template that I have no access to but they allow css changes.
Given something similar to below, such that I have the id of the second parent div but not the first parent div, is there a way I can change the background colour of the first parent div to red?
<div>
<div>First div</div>
</div>
<div id='second'>
<div>Second div</div>
</div>
I tried something like below but it didn’t work:
<style>
/* Styles for the div immediately before the second div */
#second ~ div {
background-color: red;
}
</style>
<div>
<div>First div</div>
</div>
<div id="second">
<div>Second div</div>
</div>
Is it even possible to achieve this with only CSS?
NOTE: I can only change things based on CSS as I have not access to the HTML so I cannot add an id or use javascript
4
Answers
You can use selectors level 4
:has
for this, but as of now it has limited support, currently firefox doesn’t support this.with
:has
you can do like this:Without
:has
, you need to use some javascript logic.check :has support on caniuse
It would be much easier to find the element using i.e Google Developer ‘Elements’ Tab. If you can’t do that, you might need to use JS.
You can do this by using this selector:
You can think of this selector as:
div
sdiv
s to only those that match the patterndiv + #second
, which technically will return only 1 element asid
should be uniqueIf you give the first div a parent you can handle that element’s CSS and it’s ‘div’ children with
#element > child
.