Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sass and combined child selector

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; } 
like image 254
frarees Avatar asked Sep 08 '11 09:09

frarees


People also ask

What is &__ in SCSS?

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.

Can we combine two selectors?

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.

What is the difference between '+' and '~' sibling selectors?

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.

Can you combine multiple CSS selectors?

There are different methods for combining CSS selectors: Descendant (whitespace) combinator, (Level 1) Child combinator, (Level 2) Next sibling combinator, (Level 2)


2 Answers

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 
like image 150
Arnaud Le Blanc Avatar answered Oct 13 '22 20:10

Arnaud Le Blanc


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; } } 
like image 41
BoltClock Avatar answered Oct 13 '22 20:10

BoltClock