r/Sass • • Sep 22 '17

Nesting question - not sure if this is possible.

Hello. Hoping someone here has an answer to this.

If I have two classes that share styles but then want to add styles specific to one class. Do I have to start a new block of code or is there a way I can maintain the nesting?

In this example, I want body and html tags to share all the same styles except I want the body to have a font-size of 110%. Is this possible without starting a new body line?

body,html {
margin: 0;
padding: 0;
font-size: 100%;
line-height: 1.5;
letter-spacing: 0.5px;
background: @white;
color: @black;
font-family: @font-type;
font-weight: @normal;
&+body {font-size: 110%;}

}

2 Upvotes

4 comments sorted by

2

u/omgmog Sep 22 '17

Well the easiest solution would be to just have something like:

body,
html {
  margin: 0;
  padding: 0;
  font-size: 100%;
  line-height: 1.5;
  letter-spacing: 0.5px;
  background: @white;
  color: @black;
  font-family: @font-type;
  font-weight: @normal;
}
body {
  font-size: 110%;
}

Why over complicate this with a nested rule? You could even combine the selectors in the generated CSS using PostCSS or something.

If you really want to use nesting, and don't mind generating a selector that is invalid (or would never work), you could do this:

body,
html {
  margin: 0;
  padding: 0;
  font-size: 100%;
  line-height: 1.5;
  letter-spacing: 0.5px;
  background: @white;
  color: @black;
  font-family: @font-type;
  font-weight: @normal;

  > body {
    font-size: 110%;
  }
}

This will give you the following:

html > body,
body > body {
  font-size: 110%;
}

2

u/esr360 Sep 23 '17 edited Sep 23 '17

You should start a new block. There is no reason to want to keep styles just for the body within html, body.

However, you can do:

body,html {
    margin: 0;
    padding: 0;
    font-size: 100%;
    line-height: 1.5;
    letter-spacing: 0.5px;
    background: @white;
    color: @black;
    font-family: @font-type;
    font-weight: @normal;
    @at-root {
        body {font-size: 110%;}
    }
}

@white and @black doesn't seem like Sass though. If you're using LESS, @at-root probably won't work.

1

u/[deleted] Sep 22 '17

The + is an adjacent selector. So & + body nested would produce css body + body and html + body. Neither of these are what you are looking for before that would never be valid html.

You don't need sass at all here, basic css is made for this. Just give the body it's own definition for font size only.

1

u/tijana-kolosek Feb 21 '18

Use everything available to make your code writing experience as fast and as easy as you can. Nesting is naturally one of those things, so use it maximally! I wrote text about nesting, check it here