AtoZ CSS Quick Tip: When to Use the ID Selector Code
Buying a SitePoint Premium membership will give you access to the full AtoZ: CSS series.
Welcome to our AtoZ CSS series! In this series, I’ll be exploring different CSS values (and properties) each beginning with a different letter of the alphabet. In this article I’ve added a new quick tip/lesson about the id
Selector for you.
I is for id
Selector
In the video for letter I, we looked at the id
selector and how it factors into CSS. I also had a good rant about the issues with using id
over class
, both in terms of reusability and specificity.
To balance the argument a little I should talk about when we should use ID and why.
To provide a unique hook for Javascript
This is a little outside the normal scope of CSS (although not if you believe the constant debate of whether or not we need CSS anymore) it’s a useful piece of advice none the less. The fastest and most direct way of interacting with an element with JavaScript is to target it by its id
attribute.
To provide targeted anchor tags for navigation
ID’s can be used on a single page for navigation by setting the href
in an anchor tag to the id
. Check out this example that allows you to navigate easily to different chapters on the page.
See the Pen ORyGLa by SitePoint (@SitePoint) on CodePen.
For linking form inputs with their labels
When building forms, we can link the label
of a particular input
by the for
attribute on the label
with the corresponding id
attribute of the input. This means that clicking on the label will focus a text input field or toggle the state of checkboxes or radio buttons.
And, finally, here’s one last tip about using ID’s: a valid id
cannot start with a number and must be at least one character long.