CSS selector with period in ID

HtmlCssCss Selectors

Html Problem Overview


The HTML spec allows for periods (.) in an id:

<img id="some.id" />

However, using a CSS ID selector rule will not match correctly:

#some.id { color: #f00; }

The CSS spec for ID Selectors does not mention this case. So I assume it is using the combination of a tag name and class selector? For example, a CSS rule of a.className would apply to all anchor tags (<a>) with a class name of className, like <a class="className"></a>.

Is it possible to have an external CSS file rule that references an HTML element by its id that has a period in it?

I expect not since the CSS spec specifies that a CSS "identifier" does not include the period as a valid character. So is this a fundamental mismatch between HTML and CSS specs? Is my only alternative to use a different type of CSS selection? Can anyone smarter than I confirm or deny this?

(I would remove the period from the HTML id attribute to simplify things, but it is a system-generated id, so I don't have the ability to change it in this case.)

Html Solutions


Solution 1 - Html

After digging through the specs some more, I found the CSS spec does allow for backslash (\) escaping like most languages.

So in my example, the following rule would match:

#some\.id {
  color: #f00;
}

Solution 2 - Html

You could also use the attribute selector like this:

[id='some.id'] {
  color: #f00;
}

Solution 3 - Html

Since you are using id, you can also use document.getElementById() which checks the id value as a normal string and not a CSS selector. e.g. the following works too:

const myElem = document.getElementById("some.id");

The only drawback is, you can't limit the scope of search, like you could with querySelector e.g. someElement.querySelector(). but since Ids should always be unique, a document wide search with id is valid.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJon AdamsView Question on Stackoverflow
Solution 1 - HtmlJon AdamsView Answer on Stackoverflow
Solution 2 - HtmlSDD512View Answer on Stackoverflow
Solution 3 - HtmlprefView Answer on Stackoverflow