134

I've just discovered Sass, and I've been so excited about it.

In my website I implement a tree-like navigation menu, styled using the child combinator (E > F).

Is there any way to rewrite this code with a simpler (or better) syntax in Sass?

#foo > ul > li > ul > li > a {
  color: red;
}
1
  • I think by "simpler/better" OP means "in a way that uses whitespace to indicate hierarchy"
    – jsejcksn
    Jan 9, 2019 at 20:49
238

Without the combined child selector you would probably do something similar to this:

foo {
  bar {
    baz {
      color: red;
    }
  }
}

If you want to reproduce the same syntax with >, you could to this:

foo {
  > bar {
    > baz {
      color: red;
    }
  }
}

This compiles to this:

foo > bar > baz {
  color: red;
}

Or in sass:

foo
  > bar
    > baz
      color: red
4
  • 2
    This is just going to make it longer, isn't it?
    – BoltClock
    Sep 8, 2011 at 9:26
  • 1
    I though this is what OP wants Sep 8, 2011 at 9:38
  • 1
    nice, thanks. btw, as BoltClock stated, is longer (and somehow uglier for me). Seems like I'll have to stay with my old styling.
    – frarees
    Sep 8, 2011 at 9:46
  • 1
    you need to define "nicer syntax" ;) Sep 8, 2011 at 9:48
21

For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.

However, if you had multiple rules like this:

#foo > ul > li > ul > li > a:nth-child(3n+1) {
    color: red;
}

#foo > ul > li > ul > li > a:nth-child(3n+2) {
    color: green;
}

#foo > ul > li > ul > li > a:nth-child(3n+3) {
    color: blue;
}

You could condense them to one of the following:

/* Sass */
#foo > ul > li > ul > li
    > a:nth-child(3n+1)
        color: red
    > a:nth-child(3n+2)
        color: green
    > a:nth-child(3n+3)
        color: blue

/* SCSS */
#foo > ul > li > ul > li {
    > a:nth-child(3n+1) { color: red; }
    > a:nth-child(3n+2) { color: green; }
    > a:nth-child(3n+3) { color: blue; }
}
1
  • So there's no transform for the combined child selector... maybe any alternatives to it?
    – frarees
    Sep 8, 2011 at 9:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.