Search code examples
csssass

How to apply CSS to only a particular class while the class shares other CSS code, with another class?


For example here's the HTML code:

<div class="topSection">
    <div class="middleSection">
        <p>This is some text in a paragraph.</p>
    </div>
    <div class="lowerSection">
        <p>This is some text in a paragraph.</p>
    </div>
</div>

Here is the CSS

.topSection{
    .middleSection, .lowerSection{
        padding: 20px;
        font-size: 20px
        p{
            background-color: lightgrey;
        }
    }
}

With the way this CSS is structured, I was wondering if I want to apply the p tag style to ONLY for the middleSection class, but not for the lowerSection class, how would I do that?

I was thinking to do something like this by using the :not() but this did not work:

.topSection{
    .middleSection, .lowerSection{
        padding: 20px;
        font-size: 20px
        p:not(.lowerSection){
            background-color: lightgrey;
        }
    }
}

Or is the only way to do it is by creating separate CSS code for middleSection and then apply the p tag styles to it? To me this seems like extra bit of code, to address a small issue. Is there a shorter way to address this case?


Solution

  • The :not() should apply to the parent so consider &

    .topSection {
      .middleSection,
      .lowerSection {
        padding: 20px;
        font-size: 20px;
        &:not(.lowerSection) p {
          background-color: lightgrey;
        }
      }
    }
    <div class="topSection">
      <div class="middleSection">
        <p>This is some text in a paragraph.</p>
      </div>
      <div class="lowerSection">
        <p>This is some text in a paragraph.</p>
      </div>
    </div>