Home >Web Front-end >CSS Tutorial >How Can I Use Variables in CSS Selectors with SCSS?
Using Variables for CSS Selectors in SCSS
In SCSS, variables are a powerful tool for storing dynamic values and reusing them throughout your stylesheet. However, using variables directly in CSS selectors is not straightforward.
Suppose you have a variable $gutter set to 10. You might want to use it in a selector to dynamically generate a class name based on the value of $gutter.
Problem:
If you try to use a variable in a selector directly, like this:
<code class="scss">.grid+$gutter { background: red; }</code>
It will result in an invalid CSS class. The output will not be .grid10, as expected.
Solution:
To use variables in CSS selectors, you need to use the #{$var-name} syntax. The code below demonstrates how to use the $gutter variable to generate a class name:
<code class="scss">$gutter: 10; .grid#{$gutter} { background: red; }</code>
This will generate the following CSS:
<code class="css">.grid10 { background: red; }</code>
Note that the # is required before the variable name.
Additional Note:
The #{$var-name} syntax can also be used to include variables in strings, such as in URLs:
<code class="scss">background: url('/ui/all/fonts/#{$filename}.woff')</code>
The above is the detailed content of How Can I Use Variables in CSS Selectors with SCSS?. For more information, please follow other related articles on the PHP Chinese website!