Home > Web Front-end > CSS Tutorial > How Can I Use Variables in CSS Selectors with SCSS?

How Can I Use Variables in CSS Selectors with SCSS?

Linda Hamilton
Release: 2024-11-04 03:00:02
Original
460 people have browsed it

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>
Copy after login

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>
Copy after login

This will generate the following CSS:

<code class="css">.grid10 {
    background: red;
}</code>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template