Home > OS >  npm run dev generates wrong css code from scss file
npm run dev generates wrong css code from scss file

Time:06-26

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

.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?

CodePudding user response:

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;
    }
}
  • Related