How to Import One CSS File into Another?

To import one CSS file into another you can use the @import rule. The @import rule can either be used with url() for eg. @import url(‘example.css’) or you can directly specify the file path as a string after the @import rule, for eg. @import “example.css”.

These two syntax are as follows:

@import url('file_path');

/* OR */


@import "file_path";

Example:

Let’s say we have two CSS files “example1.css” and “example2.css” and both are in the same directory. And we want to import “example2.css” file into “example1.css” file.

To do that, you have to add the @import rule at the top of your file along with the url() that contains the “example2.css” file’s path.

example1.css

/* Import example2.css file */
@import url('example2.css');


body{
    background-color: yellow;
    font-style: italic;
}

/* Other existing CSS styles.... */

Note: The @import rule must be the first rule in your CSS file (except @charset). If it is not so, the another file will not be imported into the current CSS file.

For example, if you try to add the @import rule after the body tag, the “example2.css” file will not get imported into the “example1.css” file.

body{
    background-color: yellow;
}

/* Import example2.css file */
@import url('example2.css');

/* This will not work */

Why should you avoid importing one CSS file into another?

In last few examples, we have seen how we can import one CSS file into another. But, we should always avoid importing one CSS file into another.

This is because, when you add an @import rule to import one CSS file into another, it makes an additional HTTP request to the server to load this file.

See the following image. Here, two HTTP requests are sent to the server. First to load the “example1.css” and second, to load the “example2.css” file:

import one css file into another

So, if you really care about the performance, you should always avoid adding such additional @import rules to your CSS file.

Instead, you can copy the contents of both files into a third file say “example3.css” and load only this file. This will solve your problem without sending any additional requests to the server.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.