Home > Net >  How to set styles to unrelated element if the parent has the particular class with CSS
How to set styles to unrelated element if the parent has the particular class with CSS

Time:08-11

I have a HTML structure like below.

<div class='A'>
    <div class='B' />
    <div class='C' />
</div class='A'>

<div class='D' />

What I want to achieve:

if A has C: add margin to D. (There is a chance that <C /> will not appear.)

CodePudding user response:

I don't think you can do something like that with just the markup you have.

In your template you probably have some kind of condition for the class C.

Maybe you can also add a condition to add an extra class to the class A element whenever the class C condition is true.

If class C is not rendered you will have

<div class='A'>
    ...
</div class='A'>

If it is rendered then you would have something like

<div class='A contains-c'>
    <div class='B' />
    <div class='C' />
</div class='A'>

<div class='D' />

and you could then use the following css

.contains-c   .D {
  ...
}

There is a has()css pseudo-class coming, but it still has almost no support. You can read about it here if it interests you

CodePudding user response:

You can try something like this:

.A .C ~ .D {
  margin: ....
}
  •  Tags:  
  • css
  • Related