0

How does @import works in CSS? What is the pros and cons. 🤔

 2 years ago
source link: https://dev.to/jasmin/how-does-import-works-in-css-what-is-the-pros-and-cons-136c
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Cover image for How does @import works in CSS? What is the pros and cons. 🤔
Jasmin Virdi

Posted on Apr 15

How does @import works in CSS? What is the pros and cons. 🤔

We all must have used @import in our css files for importing one stylesheet to another. While working on large projects we often make use of imports to make use of same styles in different views.

The @import statement has some pros and cons related to it. Let's first discuss how the import works over using the <link> element in HTML file.

I personally prefer to use media over text to understand any concepts and like using them in my articles as well 😅

So let's try to understand the difference between using @import and <link> element to load CSS files followed by the pros and cons of @import statement.

Working of @import statement.

In the above example we can see that importing stylesheet into one another builds dependency graph. Due to this dependency tree the base css file which is homeview.css is downloaded first and then the dependent css files are downloaded which are button.css and form.css.

Working of <link> element.

When the stylesheets are loaded using link elements they are downloaded at the same time which can be used to combine them into single file.

We have covered the major difference between the two approaches now let's focus on the pros and cons of @import statement.

Pros of using CSS @import

  1. Saves time in copy pasting the same code in every file or adding links approach.

  2. Good for building medium to large organisational projects.

  3. Create primary CSS file and then import other files like typography or images. This way of managing CSS files is simple yet effective and helps in maintaining good project structure.

Cons of using CSS @import

The only negative that comes with @import statement is increasing the page load time if not used during build process. As it goes and reads the imports and then applies them. Although the time difference is very small but can impact your search ranking where the bots use page loading time to calculate ranking.

I tried to cover all the major points which defines the flow and working of CSS @import statement in brief. 😊
Do let me know if I missed something 😉

Happy Learning! 👩‍💻


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK