(click anywhere to close)
OPEN MENU

[SASS] Import & Extend

category: Website | course: SASS | difficulty:
IN PRINT
QUICK CONTENTS:Intro
1. Importing

With mixins, we’ve seen how to save a set of declarations in a function with parameters. However, if you don’t require parameters, there’s an easier way. You can copy all the declarations from inside another selector to somewhere else by using

@extend selector;
.specialParagraphs {
	color:brown;
	font-size:10px;
}

.specialLinks {
	@extend .specialParagraphs;

	text-decoration:none;
	border-bottom:2px solid brown;
}

/*** OUTPUTS TO ***/
.specialParagraphs {
	color:brown;
	font-size:10px;
}

.specialLinks {
	color:brown;
	font-size:10px;
	text-decoration:none;
	border-bottom:2px solid brown;
}

Note, though that this selector needs to be single element (perhaps with pseudo-class or pseudo-element added to it). More complex selectors won’t work.

Additionally, SASS provides an extra type of selector called the placeholder selector. It looks like a regular class or id selector, except that the # or . is replaced by a %. These placeholder selectors will be ignored and not rendered, unless they are extended somewhere. This allows you to create styles that you know will only be extended in some stylesheets, and never used directly in your HTML – which saves space and avoids naming collisions.

%specialParagraphs {
	color:brown;
	font-size:10px;
}

.specialLinks {
	@extend %specialParagraphs;

	text-decoration:none;
	border-bottom:2px solid brown;
}

/*** OUTPUTS TO ***/
.specialLinks {
	color:brown;
	font-size:10px;
	text-decoration:none;
	border-bottom:2px solid brown;
}

Importing

And lastly, we can modularize our CSS even more by splitting it into multiple files. SASS allows us to place snippets of code inside separate files, and then import those into multiple other big files.

Such a snippet is called a partial, and requires the filename to start with an underscore (e.g., _partial.scss).

To import the snippet, we use

@import ’partial’;

The underscore and extension can be left behind; SASS knows what you mean and will figure it out.

CSS already has a native import option, but it has one large drawback; CSS creates another HTTP request for every import. Therefore, it increases server load and page load time. SASS, on the other hand, can put everything in a single file as it compiles. Yay!

The special file naming and importing syntax in SASS is, therefore, used to bypass the native importing function.

CONTINUE WITH THIS COURSE
Do you like my tutorials?
To keep this site running, donate some motivational food!
Crisps
(€2.00)
Chocolate Milk
(€3.50)
Pizza
(€5.00)