In this tutorial, our goal is to guide you on how to use SASS/SCSS, which are CSS preprocessors, in a Vite project.
By the end of this tutorial, you should be able to:
You should have a basic understanding of:
To work with SCSS, we need to install the SASS package. Navigate to your project directory and run the following command:
npm install -D sass
After installing sass, create a style.scss
file in your src
folder and write some SCSS in it:
$color: red;
body {
background-color: $color;
}
In your JavaScript or Vue file, import the SCSS file:
import './style.scss'
Vite will automatically compile and include the CSS in your application.
SCSS allows you to use variables. Here is a simple example:
$font-size: 16px;
$text-color: blue;
body {
font-size: $font-size;
color: $text-color;
}
This will compile to:
body {
font-size: 16px;
color: blue;
}
SCSS lets you nest your CSS selectors in a way that follows the same visual hierarchy of your HTML.
nav {
ul {
margin: 0;
padding: 0;
list-style: none;
}
li { display: inline-block; }
a {
display: block;
padding: 0 10px;
color: #333;
}
}
This will compile to:
nav ul {
margin: 0;
padding: 0;
list-style: none;
}
nav li {
display: inline-block;
}
nav a {
display: block;
padding: 0 10px;
color: #333;
}
In this tutorial, we have covered:
From here, you can learn more about other SCSS features like mixins, functions, and more. A good resource for this is the SASS documentation.
Exercise 1: Create a SCSS file with variables for colors and font sizes, and use them in your styles.
Exercise 2: Nest CSS selectors in your SCSS file to style a complex HTML structure.
Solutions:
Remember, the more you practice, the more comfortable you will become with SCSS. Happy coding!