1

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!

user1406440
  • 1,329
  • 2
  • 24
  • 59
  • Sounds like you should be using a seperate class and an `extend` – Paulie_D Aug 08 '17 at 13:59
  • Yeah I was looking at a few ways to do this, it was more out off curiosity. To be honest it's probably just as easy to write 'standard' CSS. Thanks! – user1406440 Aug 08 '17 at 14:53

1 Answers1

4

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.

Josh Alexy
  • 401
  • 1
  • 3
  • 13
  • Yeah some of it seems a bit long winded. To be honest I just wanted to experiment and see how many different ways it could be achieved, if it could at all. Maybe a more 'standard' CSS approach is better suited than nesting stuff for the sake of it and is a lot more readable. Thanks for your help! – user1406440 Aug 08 '17 at 14:54
  • I've decided just to target it using `h3.title-class {}`. I tried using `@at-root h3#{&}` but it wouldn't work. I think the problem is I have a few alternative `.title-class` ...so the parent is actually setup something like `.title-class-1, .title-class-2, .title-class-3 {}`. I think the multiple class separated by a comma cause the problem? – user1406440 Aug 08 '17 at 17:09
  • To avoid creating multiple rules like that, you may want to check out the [attribute selector](https://stackoverflow.com/a/5110337/4624718). You can match any class that has the word `title-class` in it. – Josh Alexy Aug 08 '17 at 18:48