user1406440
user1406440

Reputation: 1655

Class styled depending on element (h2/h3) with nested SCSS/ampersand?

I feel like I'm missing something pretty obvious here, I can write the CSS for it but I want to know if there's a way to do it with nested SCSS. If you have styling on a class, is it possible to adjust the style if that class is on a different element. For example an h2 and then an h3. I know you can do it with an additional classes, like...

.title-class {
    background-size: 30px;
    font-size: 30px;

    &.another-class {
        background-size: 20px;
        font-size: 20px;
    }
}

Which would render as .title-class.another-class {}

What I'm after is a base class of .title-class {} and the nested style as h3.title-class {} - Is it possible?

I thought something like the following (in theory) which obviously doesn't work! I tried using @root but my understanding of that is minimal so I couldn't get that to work.

.title-class {
    background-size: 30px;
    font-size: 30px;

    &h3 {
        background-size: 20px;
        font-size: 20px;
    }
}

Thanks in advance!

Upvotes: 2

Views: 2154

Answers (1)

Josh Alexy
Josh Alexy

Reputation: 411

If you're trying to target all h3 elements with a class of title-class, without using the @root directive you would use the following:

h3 {
  &.title-class {
    color: blue
  }
}

Check out this already answered question if you'd like to use the root directive, although I feel personally it is a bit of an over complication in this scenario.

Upvotes: 5

Related Questions