Skip to main content

How to style HTML5 id and class that start with a number

What? Didn’t you come across this kind of situation when you have tried to name html class or id with a number but couldn’t style it with our predefined hash tag (#) and dot (.) in CSS? Here is the solution.

We can start our html5 id or classe with a number. For example <div class=”1”>. Now our lovely css has some egoistic behavior towards html and it will not let you style that particular element with our default hash tag (#) and dot (.). For example, this code will not work to style that specific element.


.1{
Color:#333;
}

Why?

Well, W3C got some specification on it.
So, here’s the solution to style this kind of stuff. You can use an attribute selector as mentioned in the specification of W3C.


[class=”1”]{
Color:#333;
}

Second solution is that you can use Unicode character instead of a number. Here is the example.


.\35{
Color:#222;
}

Kinds of weird solution then attribute selectors, right? Yup and a bit difficult but using an attribute selectors has also some problems with the older browsers and the only solution I can give you is to use Unicode selectors to support older browsers.

Same rules are defined for ids. You have to use either an attribute selector or Unicode selector to style your html element in css. Here is the example:


<div id=”5”>
  Your markup
</div>

with use of attribute selector:


[id=”5”]{
Color:#222;
}

with use of Unicode selector:


#\35{
Color:#222;
}

Thanks for reading, Hope you find this useful.