njho
njho

Reputation: 2158

SCSS/SASS - How to Specify Two Valid Parents for Nested CSS

Question: With SCSS, can we specify two different .main selectors? Say I want another one with margin-top: 50px while also inheriting all other conditions

I have inherited some SCSS from someone else. I have the following SCSS structure:

.main {
  margin-top: 74px;

  ul.tabs {
    position: relative;

    li.tab {
     /*The rest of nested structure*/
             }
          }
       }

It continues to nest (unfortunately) for many layers.

I have some other options (splitting the structure in two) which is a simple fix. Just curious if there's something better.

Thanks!

Upvotes: 1

Views: 973

Answers (2)

Erin Halbmaier
Erin Halbmaier

Reputation: 354

If you use a placeholder, as long as one selector is not inside a media query, it should group them together in the CSS. Ie

%mainStyles {
        border: 1px solid black;
}

.main1 {
    margin-top: 75px;
    @extend %mainStyles;
}

.main2 {
      margin-top: 50px;
      @extend %mainStyles;
}

Should generate

.main1, .main2 {
     border: 1px solid black;
}
.main1 {
    margin-top: 75px;
}

.main2 {
      margin-top: 50px;
}

Upvotes: 1

Our_Benefactors
Our_Benefactors

Reputation: 3539

You should use a mixin:

@mixin sharedStyles{
  //shared nested styles go here
}

.parentA{
  margin-top:74px;
  @include sharedStyles;
}

.parentB{
  margin-top: 50px;
  @include sharedStyles;
}

Here is a gist that illustrates the concept:

https://gist.github.com/Ryan-Haines/ba10888d0828d394851d3da6063f70bb

I recommend using sassmeister for rapid prototyping:

https://www.sassmeister.com

Upvotes: 1

Related Questions