0

I try to apply a different CSS if the element title has or doesn't have a child with the class find. Is it possible to do it only with CSS ?

Case 1:

 <h2 class="title">
    <span class="ico"></span>
    <span class="find">Find</span>
</h2>

.title {
    padding-left: 4px;
}

Case 2:

 <h2 class="title">
    <span class="ico"></span>
    Find
</h2>

.title {
    padding-left: 9px;
}
GtAntoine
  • 1,049
  • 1
  • 8
  • 12

1 Answers1

0

You can use the parent selector, has():

.title:has(.find) {
    padding-left: 4px;
}

.title {
    padding-left: 9px;
}

You should following way to apply styling to element or class. There is a parent class .title Now title have nested 2 class .ico is mandatory and .find is optional.

so when you want to apply CSS with the nested element you should use following way .parent .child eg. .title .find

I have defined default style with .title. Whenever .find does not exist, it will inherit styles of the parent class. In our case, I have set default style as font-size:15px

In the stylesheet, you seem that I have used .title .find, it will apply styles declared in stylesheet where the parent is .title and it will apply to all child have .find class. In our case, I have set default style as font-size:22px

*{
font-family: "Arial";
}

.title{
  font-size:15px;
}

.title .find{
    font-size:22px;
}
<h2 class="title">
    <span class="ico"></span>
    <span class="find">Find</span>
</h2>

<h2 class="title">
    <span class="ico"></span>
     Find
</h2>
Mikael Dúi Bolinder
  • 2,080
  • 2
  • 19
  • 44
Dipak
  • 2,248
  • 4
  • 22
  • 55