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
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
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 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.
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.
Front-end dev and teacher at The General Assembly London. A to Z CSS Screencaster, Founder of sapling.digital and Co-founder of The Food Rush.