Bram Vanroy
Bram Vanroy

Reputation: 28427

Nested selectors in SASS/SCSS

I am a bit confused with how nested selectors work in SASS/SCSS.

This:

#wrapper {
    font: {
        weight: 400;
        size: 13px;
    }
    line-height: 1.2;
    color: #fff;
    > .de1, .de5{margin: auto;}
}

compiles to this:

#wrapper {
  font-weight: 400;
  font-size: 13px;
  line-height: 1.2;
  color: #fff;
}
#wrapper > .de1, #wrapper .de5 {
  margin: auto;
}

But what if I wanted to have an end result that does not include .de5

#wrapper > .de1, .de5 {
  margin: auto;
}

Is that even possible? I thought extending the .de5 selector but that didn't work out.

#wrapper {
  font: {
    weight: 400;
    size: 13px;
  }
  line-height: 1.2;
  color: #fff;
  > .de1 {margin: auto;}
}
.de5 {@extend .de1;}

Compiles to

#wrapper {
  font-weight: 400;
  font-size: 13px;
  line-height: 1.2;
  color: #fff;
}
#wrapper > .de1, #wrapper > .de5 {
  margin: auto;
}

How can I get .de5 without #wrapper >?

(I tested the SCSS on SassMeister)

Upvotes: 1

Views: 900

Answers (4)

Hamid Yaftian
Hamid Yaftian

Reputation: 145

If you want to have the same Code for .de1 and .de5 but with different selector, you can use "mixin" and "include". somthing like this:

@mixin margin {
margin: auto; 
}
#wrapper {
  font: {
    weight: 400;
    size: 13px;
  }`enter code here`
  line-height: 1.2;
  color: #fff;
  > .de1 {@include margin}
}
.de5 {@include margin}

I think it can help you. Live Demo: http://sassmeister.com/gist/a19ef9d026a756144cad

Upvotes: 0

morkro
morkro

Reputation: 4655

Use a placeholder instead.

SCSS

%placeholder {
  margin: auto;
}

#wrapper {
    font: {
        weight: 400;
        size: 13px;
    }
    line-height: 1.2;
    color: #fff;

    > .de1 {
      @extend %placeholder;
    }
}

.de5 {
  @extend %placeholder;
}

CSS

#wrapper > .de1, .de5 {
  margin: auto;
}

#wrapper {
  font-weight: 400;
  font-size: 13px;
  line-height: 1.2;
  color: #fff;
}

Link to SassMeister: http://sassmeister.com/gist/32ac4c0aa0f708a0d4e3

Upvotes: 0

Simon Arnold
Simon Arnold

Reputation: 16157

I think you need to do it the other way around.

.de5 { margin: auto; }
#wrapper {
    >.de1 { @extend .de5 }
}

Upvotes: 0

BoltClock
BoltClock

Reputation: 723388

Perhaps do it the other way around? Declare the margin for .de5 and have #wrapper > .de1 extend that instead:

.de5 {
  margin: auto;
}

#wrapper {
  font: {
    weight: 400;
    size: 13px;
  }
  line-height: 1.2;
  color: #fff;
  > .de1 {
    @extend .de5;
  }
}

Upvotes: 2

Related Questions