CSS Properties
CSS @import Rule
Photo Credit to CodeToFun
🙋 Introduction
The @import
rule in CSS allows you to import one or more external style sheets into a CSS file. This can be useful for organizing your CSS by separating styles into different files or reusing styles across multiple pages.
The @import
rule must be placed at the top of the CSS file before any other rules.
💡 Syntax
The syntax for the @import
rule is simple. You specify the URL or the path to the CSS file you want to import:
@import url("style.css");
You can also use the @import
rule with optional media queries to conditionally apply styles based on the device's characteristics:
@import url("print.css") print;
🎛️ Default Value
The @import
rule itself doesn't have a default value. However, the imported CSS file must follow the default styling rules of the CSS it includes unless overridden.
🏠 Property Values
Value | Description |
---|---|
url | The path or URL of the CSS file you want to import. This can be a relative or absolute URL. |
media queries | Specify media types such as screen, print, or conditions like min-width, max-width for applying styles only under certain conditions. (This is optional) |
📄 Example
In this example, we will import an external style sheet into another CSS file.
/* main.css */
@import url("reset.css");
body {
font-family: Arial, sans-serif;
color: #333;
}
Here, the reset.css file is imported at the top, and the styles defined in main.css will be applied after the styles from reset.css.
Conditional Import with Media Query
In this example, the imported CSS file will only be applied if the device is in print mode.
/* print.css */
@import url("print-styles.css") print;
body {
font-size: 12pt;
color: #000;
}
🖥️ Browser Compatibility
The @import
rule is widely supported across all modern browsers, including Chrome, Firefox, Safari, Edge, and Internet Explorer. However, keep in mind that using @import
can slightly delay the loading of styles since it requires an additional HTTP request. For performance reasons, it's often better to link stylesheets directly in the HTML or combine multiple CSS files into one.
🎉 Conclusion
The @import
rule in CSS provides a simple way to manage and organize your stylesheets by importing external CSS files into your main stylesheet. While it is convenient for structuring your CSS, be mindful of the potential performance implications. Use @import
wisely, especially in larger projects where loading times and performance are critical.
👨💻 Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (CSS @import Rule), please comment here. I will help you immediately.