I Like It Sassy is a series of Sass tutorials, you can find the other articles below:
By now, you should know how to create variables and mixins. Great! This time, let’s learn how to import files, to keep them organized, and how CSS rules can inherit properties.
Import
In order to keep your project organized, you can separate your SCSS files into different files and then import them into another file. In CSS, the @import rule will create an additional HTTP request; on the other hand, in Sass, that is not the case. Instead @import just combines it, in essence, only a single CSS file will be served to the browser. That’s because the SCSS will be compiled into a CSS file later.
The normalize.scss file that we would like to import:
// _normalize.scss html, body, ul, ol margin: 0 padding: 0
Let’s say that you have a style.scss file, you should use the following code:
SCSS: // import the normalize.scss file @import 'normalize'; // import the normalize.scss in a partials folder @import 'partials/normalize'; Sass: // import the normalize.scss file @import 'normalize' // import the normalize.scss in a partials folder @import 'partials/normalize'
Remember, each partial file should start with an underscore like so: _normalize.scss, _reset.scss, _navigation.scss etc. Don’t worry, Sass is smart enough to find the _normalize.scss file using ‘normalize’ (without underscores). In short, you can use the import rule to make your project directory much more readable.
Inheritance
Inheritance? In Sass? Yes, just like Object Oreinted programming, you can inherit properties and values from other selectors.
SCSS: .header { background: green; width: 100%; height: 50px; } .header-text { extend .header; color: white; } Sass: .header background: green width: 100% height: 50px .header-text extend .header color: white
The Sass file will be compiled into this:
.header { background: green; width: 100%; height: 50px; } .header-text { background: green; width: 100%; height: 50px; color: white; }
Inheritance can be incredibly useful. Now that you have learned about how to import and the inheritance features work, you can use them to your advantage. Have fun coding! If you would like to learn more about Sass, take a look at the Sass Way.
If you have any questions, please leave a comment below.