CSS @import issue

91 views Asked by At

I was trying to add my other CSS file to my project's main CSS file, but @import is not working for the second one. what should I do?

Screenshot of the problem of using @import

I was hoping to upload multiple CSS files import them to the main one and link the main css file with my html file.

1

There are 1 answers

2
Fabio Guimaraes On

Hello Siyam Zaman Shishir,

Great effort on your part! Just a couple of tweaks for optimization:

The @import statements should directly reference your files:

@import url(./library.css);
@import url(./screen.css);

You've set the background-color in both the style.css and screen.css, causing a conflict due to CSS hierarchies. To resolve this, simply add !important within the @media statement in screen.css:

@media only screen and (max-width: 767px) {
  body {
    background-color: red !important;
  }
}

I made a test just like your project. Let me share what I did here:

  1. The files: C:\Project\test C:\Project\test\index.html C:\Project\test\css C:\Project\test\css\library.css C:\Project\test\css\screen.css C:\Project\test\css\style.css
  2. HTML:
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport"
                content="width=device-width,
                initial-scale=1">
            <link rel="stylesheet"
                href="./css/style.css">
            <title>log in</title>
        </head>
        <body>
    
        </body>
    </html>
    
  3. style.css
    @import url(./library.css);
    @import url(./screen.css);
    
    body{
        background-color:
            var(--color-bg);
    }
    
  4. library.css
    :root{
        --color-bg: #CCC;
    }
    
  5. screen.css
    @media (max-width: 767px) {
      body{
         background-color: red !important;
      }
    }
    

It is working as expected!
screen test
If you have any questions, feel free to ask.

Best regards, Fabio.