Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

npm run dev generates wrong css code from scss file

I have a small project in Laravel, and I’m using npm run dev to compile a scss file, but the css file that is generated has an error, now I’ll show you.

This is the scss code

.nav-link {
    color: $color_light;
    font-weight: 600;
    font-size: 1.5em;

    :hover {
    color: $color_vLight;
    }
}

And this is the css code that is generated after running npm

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.nav-link {
  color: rgb(214, 214, 214);
  font-weight: 600;
  font-size: 1.5em;
}
.nav-link :hover {
  color: rgb(247, 247, 247);
}

As you can see, the compiling process put a space before :hover, that causes an error in the web page, if I edit the css file manually and remove the space, the web page works fine. Is there a way to fix this? I’m not quite sure about tampering with the package.json or package-lock since I’m not sure about what could be wrong.

Did someone had a similar problem?

>Solution :

If you change :hover to &:hover the nested selector will compile as expected. In your original code, the :hover selector was nested in .nav-link but because it didn’t refer directly to the parent selector when nesting, it compiles as two separate selectors e.g. .nav-link :hover.

Using the Sass Ampersand & we can perform "chained" nesting. The & always refers to the parent selector when nesting. You can think of it as a pointer to the parent selector where & refers to .nav-link in your example. Therefore, when we do:

.nav-link {
    &:hover {
        color: #f06;
    }
}

It compiles to .nav-link:hover {} as the & makes the nested :hover definition refer directly to the parent selector .nav-link. Below is the updated code:

.nav-link {
    color: $color_light;
    font-weight: 600;
    font-size: 1.5em;

    &:hover {
      color: $color_vLight;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading