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; }
The parent selector, & , is a special selector invented by Sass that's used in nested selectors to refer to the outer selector. It makes it possible to re-use the outer selector in more complex ways, like adding a pseudo-class or adding a selector before the parent.
The descendant combinator — typically represented by a single space (" ") character — combines two selectors such that elements matched by the second selector are selected if they have an ancestor (parent, parent's parent, parent's parent's parent, etc) element matching the first selector.
2 Answers. Show activity on this post. + will only select the first element that is immediately preceded by the former selector. ~ selector all the sibling preceded by the former selector.
There are different methods for combining CSS selectors: Descendant (whitespace) combinator, (Level 1) Child combinator, (Level 2) Next sibling combinator, (Level 2)
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
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With