Reputation: 168239
Is there a way to write this css:
div.some-class{
...
}
span.some-class{
...
}
as something like this using scss?
.some-class{
&div{
...
}
&span{
...
}
}
I tried the above, but it returns an error.
Upvotes: 1
Views: 1116
Reputation: 1662
It depends what you're trying to do.
The example you show will be interpreted as .some-classdiv
and .some-classspan
which will result in a compilation error. Essentially the ampersand represents the parent selector.
If div.some-class
and span.some-class
don't share the same styles, the first block you have is still the most effective way to write it.
If they share some of the same styles, you could write a mixin.
// Shared Styles
@mixin some-class {
background: #f00;
color: #fff;
}
div.some-class {
@include some-class;
... other styles
}
span.some-class {
@include some-class;
... other styles
}
You could also @extend
an existing class:
.some-class {
background: #f00;
color: #fff;
}
div.some-class {
@extend .some-class;
... other styles
}
span.some-class {
@extend .some-class;
... other styles
}
If you extend an existing class, the class must be a root class included in the file (i.e. it can't be a nested class).
That said, since both elements have the class some-class
, you could just as easily define regular CSS:
.some-class {
background: #f00;
color: #fff;
}
div.some-class {
... other styles
}
span.some-class {
... other styles
}
Upvotes: 2
Reputation: 68339
I know there's a real desire to have your code grouped together in nice neat little blocks like that, but it just isn't possible. The error you get when you compile the code is quite clear:
>>> Change detected at 14:46:18 to: test.scss
error sass/test.scss (Line 2: Invalid CSS after " &": expected "{", was "div{"
"div" may only be used at the beginning of a compound selector.)
Of course, if you reverse it so that it is div&
, then you get this error:
>>> Change detected at 14:48:01 to: test.scss
error sass/test.scss (Line 2: Invalid CSS after " div": expected "{", was "&{"
"&" may only be used at the beginning of a compound selector.)
Your only option is to not nest at all.
.some-class {
...
}
div.some-class {
...
}
span.some-class {
...
}
Upvotes: 2