Explain Codes LogoExplain Codes Logo

Css selector with period in ID

html
css-selectors
id-names
escape-hatch
Nikita BarsukovbyNikita Barsukov·Aug 24, 2024
TLDR

Need to style an HTML element with an ID containing a period? In CSS, you escape the period with a backslash (\):

#my\.id { /* Turns the heat up on #my.id */ color: hotpink; }

Here, <div id="my.id"></div> meets its perfect match with #my\.id, treating the period as part of the ID and lets the styles sizzle!

Standoff between HTML and CSS

HTML allows periods in ID names but in CSS, a period without the escape hatch — the backslash, crafts a class selector. Hence the #my.id could be misread as targeting an ID my with a class id. Can see the chaos now?

Playing safe with selectors

Fret not, we have got multiple tactics to avoid CSS going rogue on us.

Escape with a backslash

Utilise the CSS ninja backslash (\) which informs the CSS parser to consider subsequent special character literally.

#toy\.story { /* Ride like the wind, Bullseye! */ font-size: 1.5em; }

Attribute selectors to the rescue

Alternatively, you can get attribute selectors in the game using [id='my.id']. Here, you're making CSS see the entire ID as a singular attribute, no conflicts!

[id='my.id'] { /* Something borrowed, something blue. */ background-color: blue; }

The JavaScript loophole

document.getElementById('my.id') has no qualms with periods in ID but do remember to keep your IDs unique to keep the document neat and avoid surprises.

Stepping up your selector game

Unicode characters, anyone?

If you ever need to include Unicode characters in IDs, CSS has a trick up its sleeve there too! Emit a backslash followed by the hex code. #\31 a2b would select an ID of 1a2b — now isn't that neat!

Scoped styles madness

Using scoped CSS, like the ones produced by modern JS frameworks? Stay alert as auto-generated scoped IDs might come with periods and other special characters which need escaping.

Upkeep and optimization

Validators at your service

Hack away confidently by testing your selectors and style rules with tools like the W3C CSS Validator. Don't get marooned with lousy CSS!

CMS can be messy

If your IDs are being regularly updated via a CMS or user input, sanitize IDs to remove periods or resort to JavaScript that plays along nicer with ID formats.

Ensuring browser compatibility

Test your CSS across different browsers to ensure that your escaped selectors aren't escaping your desired styles.

Striving for cleaner code

For maintainability, stick to simpler IDs or adjacent classes than complex ID names with periods. You'll thank yourself later!