Learn how to use the CSS @import rule to import stylesheets.
The CSS @import at-rule allows you to import CSS stylesheets into other CSS stylesheets. It’s practical for websites with a big/growing codebase.
Basic usage:
@import url(variables.css);
This method allows you to separate your CSS styles into individual files for variables, typography, colors, spacing, etc. — as opposed to keeping all your styles in one big stylesheet.
You can then import all your individual CSS files into your main CSS stylesheet to to add them all together:
/* Your main.css CSS file */
@import url(variables.css);
@import url(elements.css);
@import url(colors.css);
@import url(typography.css);
@import url(spacing.css);
This is a practical way to keep everything clean organized as your codebase grows over time.
Important when using @import
The most important thing to know when using @import
is that you must put your @import
statements at the very top of your main CSS file (the one that you import all your CSS files into).
Example:
/*
Your main.css CSS file
Don’t add CSS above your import statements!
*/
@import url(variables.css);
@import url(elements.css);
@import url(colors.css);
@import url(typography.css);
@import url(spacing.css);
/*
You can add CSS below
*/
.other-stuff {
padding: 16px;
background-color: blue;
}
If you put any CSS styling (in your main CSS file) above the @import
statements, it will be ignored.
Using @import with media queries
You can also use @import
statements to import CSS stylesheets conditionally. For example, if you have a specific stylesheet that should only get loaded on small screens, like smartphones, you control that by attaching media queries to your @import
statements:
@import "mobile.css" screen and (max-width: 768px);
In the example above, the mobile.css
stylesheet will only take effect on screens with a max-width of 768 pixels.