1

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

Mark
  • 3,138
  • 5
  • 19
  • 36

4 Answers4

2

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:

div:has(~#second) {
   background-color: red;
}

Without :has, you need to use some javascript logic.

check :has support on caniuse

<style>
  div:has(~#second) {
    background-color: red;
  }

</style>

<div>
  <div>First div</div>
</div>
<div id="second">
  <div>Second div</div>
</div>
Madan Bhandari
  • 2,094
  • 2
  • 26
  • 46
1

You can do this by using this selector:

div:has(+ #second) {
  background-color: red;
}

You can think of this selector as:

  1. Selecting all divs
  2. Filtering divs to only those that match the pattern div + #second, which technically will return only 1 element as id should be unique
Artur Minin
  • 271
  • 1
  • 10
0

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.

// Find the element of known id using getElementById
const targetDiv = document.getElementById("second");

// Get the previous child of the elements parent
const previousDiv = targetDiv.previousElementSibling;
7sne
  • 70
  • 3
  • 7
0

If you give the first div a parent you can handle that element's CSS and it's 'div' children with #element > child.

<style>
  #firstParent > div {
    background-color: red;
  }
</style>

<div id="firstParent">
  <div>First div</div>
</div>
<div id="second">
  <div>Second div</div>
</div>