The following is meant to toggle stylesheets:
body.light {
background: var(--bg);
color: var(--text);
& a {
color: var(--link_color);
}
}
body.dark {
color: var(--bg);
background: var(--text);
& a {
color: white;
}
}
This snippet is in the last loaded file, amongst a few CSS files.
Problem: while the attributes are executed properly, the nesting for the selectors is not being picked up (It was expected the ampersand was the proper way to go).
There is a framework CSS file (loaded before the file where this code is placed) and it is those attributes that are executed.
What are the syntactic requirements to run properly nested selectors (be they native tag selectors (such as `a) or user-defined selectors?
update
The theme is being generated via a cookies[:theme]
and the body tag adopts it this way:
<body >
CodePudding user response:
To make it work in regular CSS, rewrite without use of &
.
Exmaple:
body.light {
background: var(--bg);
color: var(--text);
}
body.light a {
color: var(--link_color);
}
body.dark {
color: var(--bg);
background: var(--text);
}
body.dark a {
color: white;
}
Regarding the ampersand, according to Sass document:
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.
Currently, usage of &
will require a css preprocessor like Sass, and also the &
is widely adopted by many syntax such as Sass, SCSS, Less.
CodePudding user response:
CSS nesting is not possible with standard CSS but only with CSS preprocessors like Sass and Less.
Caniuse.com says
CSS nesting provides the ability to nest one style rule inside another, with the selector of the child rule relative to the selector of the parent rule. Similar behavior previously required a CSS pre-processor.
but the page does not shows any supported browser.
There are some more information on developer.chrome.com. The examples use the >
character.
CodePudding user response:
This is because, you used Sass in your project. Sass is a preprocessor scripting language that compiled into CSS. Sass reduces repetition of CSS and therefore saves time. Let say you have this kind of HTML.
<div >
parent
<div >
child
<div >container</div>
</div>
</div>
assume you need these requirements, you need to make container class
to add background
to green. and desc class
to width
500px.
you can do this by,
.parent {
.container {
background: green;
&.desc {
width: 500px;
}
}
}
One Note, In order to use Sass, you have to enable it from your project.If you use Angular,Vue or React, use
npm i sass
I hope this make sense to you.