purgecss icon indicating copy to clipboard operation
purgecss copied to clipboard

[Bug]: A `:hover` in a nested rule is reported as useless

Open regseb opened this issue 2 years ago • 1 comments

Describe the bug

A :hover in a nested rule is reported as useless.

To Reproduce

  • package.json

    {
      "name": "testcase",
      "version": "1.0.0",
      "type": "module",
      "dependencies": {
        "purgecss": "5.0.0"
      }
    }
    
  • index.html

    <!doctype html>
    <html>
      <head>
        <meta charset="utf-8" />
        <title>Test case</title>
        <link href="style.css" rel="stylesheet" />
      </head>
      <body>
        <a href="https://github.com/">GitHub</a>
      </body>
    </html>
    
  • style.css

    a:hover {
      background-color: green;
    }
    
    a {
      &:hover {
        color: red;
      }
    }
    
  1. npm install
  2. npx purgecss --css style.css --content index.html --rejected
[{
  "css": "a:hover {\n    background-color: green;\n}\n",
  "file": "style.css",
  "rejected": ["&:hover"]
}]

Expected Behavior

[{
  "css": "a:hover {\n    background-color: green;\n}\n\na {\n    &:hover {\n        color: red;\n    }\n}\n",
  "file": "style.css",
  "rejected": []
}]

Environment

  • Ubuntu: 22.04.3 LTS
  • Node.js: v18.17.1
  • npm: 9.8.1
  • purgecss: 5.0.0

Add any other context about the problem here

No response

Code of Conduct

  • [X] I agree to follow this project's Code of Conduct

regseb avatar Sep 04 '23 13:09 regseb

For anyone coming across this (over a year later!), adding & to the safelist seems to work?

npx purgecss --css style.css --content index.html --rejected --safelist "&"

I'm not sure I've thought through all the edge cases, but here's my test case:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Test case</title>
    <link href="style.css" rel="stylesheet" />
  </head>
  <body>
    <a class="foo">Hey <span class"bar">World</span></a>
    <a href="https://github.com/">Git<span>Hub</span></a>
  </body>
</html>
a:hover {
  background-color: green;
}

a {
  &:hover {
    color: red;
  }

  &.foo {
    color: purple;
  }

  &.not-used {
    color: pink;
  }

  span {
    color: yellow;
  }
}

.foo {
  .bar {
    color: orange;
  }

  .not-used-nested {
    color: cyan;
  }
}

.not-used-parent {
  &:hover {
    color: blue;
  }
}

This gives "rejected":["&.not-used",".not-used-nested",".not-used-parent"].

fongandrew avatar Jan 31 '25 06:01 fongandrew