Ignoring Selectors

One of the most critical features of UnCSS is the ability to prevent it from removing specific selectors. This is essential for styles that are not present on initial page load but are added later through user interaction or other dynamic means.

Why Ignore Selectors?

UnCSS only analyzes the state of the DOM after the page loads and initial JavaScript has executed. It does not simulate user interactions. Common scenarios where you need to ignore selectors include:

  • Styles for classes added on user events like :hover, :focus, or click.
  • Dropdown menus, modals, or tabs that are hidden by default and shown with JavaScript.
  • Classes used by third-party libraries that might be initialized after UnCSS has finished its analysis.
  • Styles for content loaded via AJAX after the initial page load.

UnCSS provides two primary methods for ignoring selectors: the ignore option and inline comments.

Method 1: The ignore Option

The ignore option is a configuration setting that takes an array of strings or regular expressions. It's best for defining global patterns or ignoring selectors from third-party libraries.

Ignoring with String Literals

Provide the exact selectors you want to keep.

// In your Node.js script or .uncssrc file
{
  "ignore": [".fade", ".in", "#my-modal"]
}

Ignoring with Regular Expressions

Regular expressions are powerful for ignoring groups of selectors, such as those prefixed for JavaScript hooks.

// In .uncssrc, use string format for regex
{
  "ignore": ["/^\.js-/", "/modal-/"]
}

// In a JavaScript file, you can use RegExp objects directly
{
  ignore: [/^\.js-/, /modal-/]
}

Method 2: Inline CSS Comments

For more granular control, you can add special comments directly into your CSS files. This is ideal for one-off cases or when working directly in a stylesheet.

Single-Rule Ignore

To ignore a single CSS rule, place /* uncss:ignore */ on the line directly before it.

/* uncss:ignore */
.my-dropdown-menu {
  /* This entire rule will be kept, even if not found in the HTML */
  display: none;
  position: absolute;
}

.another-rule {
  /* This rule will be processed normally */
  color: blue;
}

Block-Level Ignore

To ignore a whole block of CSS rules, wrap them with /* uncss:ignore start */ and /* uncss:ignore end */.

/* uncss:ignore start */

.modal-backdrop {
  background-color: rgba(0,0,0,0.5);
}

.modal.is-open {
  display: block;
}

/* uncss:ignore end */

All rules between these two comments will be preserved in the final output.

When to Use Which Method

  • Use the ignore option for broad, project-wide rules, patterns (like js- prefixes), or selectors from external libraries where you don't want to modify the source code.
  • Use inline comments for specific, one-off rules within your own codebase. It keeps the ignore logic close to the code it affects, making it easier to maintain.