Home > Article > Web Front-end > How Can You Use Variables in Selectors in SCSS?
Variable Interpolation in Selectors
In SCSS, variables store values that can be referenced throughout the stylesheet. However, using variables directly as selectors poses certain limitations. Let's explore this scenario and find a solution.
The Challenge: Using Variables in Selectors
You have a variable $gutter set to 10 and want to use it in a selector .grid $gutter. This code attempts to create a class .grid10 with a red background. However, it fails to compile.
Solution: Interpolation with #{$}
To use variables in selectors, we need to employ interpolation using the #{$} syntax. Here's how:
<code class="scss">$gutter: 10; .grid#{$gutter} { background: red; }</code>
By enclosing the variable $gutter within #{$}, we interpolate its value into the selector string, resulting in .grid10. This will generate the desired CSS:
<code class="css">.grid10 { background: red; }</code>
When used in a string, such as for a URL, interpolation works similarly:
<code class="scss">background: url('/ui/all/fonts/#{$filename}.woff');</code>
Additional Notes:
The above is the detailed content of How Can You Use Variables in Selectors in SCSS?. For more information, please follow other related articles on the PHP Chinese website!