skip to Main Content

I have HTML Like this

<element1 class="class__1">
   <element2 removePadding></element2>
   <element3 class="class-3"></element3>
</element>

I want to change the margin-bottom of class-3 only when element2 has removePadding attribute, I tried like this

element1 element2[removePadding] element1 element3.class-3 {
    margin-top: 20px;
}

but this didn’t work.

I want to target that class-3 only when element2 has removePadding attribute

3

Answers


  1. element1 element2[removePadding] element1 – The last element1 shouldn’t be there, CSS selectors only can go down, not up. Furthermore element3 is not child of element2 but is a sibling so you could use the + (next-sibling) selector

    div div[data-removePadding] + div.class-3 {
        margin-top: 20px;
        background: red;
    }
    
    div {
      border: 1px solid #020202;
      padding: 5px;
      box-sizing: border-box;
    }
    <div class="class__1">
       <div data-removePadding=""></div>
       <div class="class-3"></div>
    </div>
    Login or Signup to reply.
  2. Try using a combination of the sibling selector with the class-3 selector:

    element1 element2[removePadding] ~.class-3 {
       margin-bottom: ...
    }
    

    As the other comment mentioned, CSS selectors can only go down/next and not up/previous.

    Login or Signup to reply.
  3. You can use :has pseudo-class and the child combinator (>) to achieve the wanted result!

    element1:has( > element2[removePadding] ) > element3.class-3 {
      /* your code goes here */
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search