# css-escape
[](#contributors-)
[](https://crates.io/crates/css-escape)
[](https://docs.rs/css-escape)
[](https://github.com/trananhtung/css-escape/actions/workflows/ci.yml)
[](#license)
**Escape a string for use as a CSS identifier** — a faithful implementation of the
CSSOM [`CSS.escape()`](https://drafts.csswg.org/cssom/#the-css.escape()-method)
algorithm (the same one behind the [`css.escape`](https://www.npmjs.com/package/css.escape)
npm package). Turn arbitrary text into something safe to drop into a selector,
class, or id. Zero dependencies and `#![no_std]`.
```rust
use css_escape::escape;
// Safely target an element by id, whatever the id contains.
assert_eq!(format!("#{}", escape("a b#c")), "#a\\ b\\#c");
assert_eq!(escape("0first"), "\\30 first"); // a leading digit is escaped
assert_eq!(escape(".foo"), "\\.foo"); // punctuation is backslash-escaped
assert_eq!(escape("café"), "café"); // non-ASCII passes through
```
## Why css-escape?
Building a CSS selector by concatenating a user-supplied id or class is a footgun:
spaces, dots, `#`, leading digits, and more all break the selector (or worse). The
browser solves this with `CSS.escape`, but Rust had no equivalent for scrapers,
SSR, and DOM tooling. This is that one focused, spec-exact function.
```toml
[dependencies]
css-escape = "0.1"
```
## API
| `escape(value)` | Escape `value` as a CSS identifier (CSSOM `CSS.escape()`) |
## Behavior
- Implements the CSSOM `CSS.escape()` algorithm exactly: `NUL` → `U+FFFD`; C0
controls and `DEL` → `\<hex> `; a leading digit (or a digit right after a leading
`-`) → `\<hex> `; a lone `-` → `\-`; `U+0080`+, `-`, `_`, and ASCII alphanumerics
pass through; everything else is backslash-escaped.
- Escapes **identifiers** (selectors, class/id names). Producing a quoted CSS string
value is a different operation — it must also escape newlines and control
characters — and is out of scope.
## `no_std`
`#![no_std]` (needs only `alloc`) with zero dependencies.
## Contributors ✨
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome — code, docs, bug reports, ideas, reviews! See the [emoji key](https://allcontributors.org/docs/en/emoji-key) for how each contribution is recognized, and open a PR or issue to get involved.
Thanks goes to these wonderful people:
<table>
<tbody>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/trananhtung"><img src="https://avatars.githubusercontent.com/u/30992229?v=4?s=100" width="100px;" alt="Tung Tran"/><br /><sub><b>Tung Tran</b></sub></a><br /><a href="https://github.com/trananhtung/css-escape/commits?author=trananhtung" title="Code">💻</a> <a href="#maintenance-trananhtung" title="Maintenance">🚧</a></td>
</tr>
</tbody>
</table>
## License
Licensed under either of [Apache-2.0](LICENSE-APACHE) or [MIT](LICENSE-MIT) at
your option.