skip to Main Content

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


  1. 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>
    Login or Signup to reply.
  2. 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;
    
    Login or Signup to reply.
  3. 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
    Login or Signup to reply.
  4. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search