- Published on
One of a kind: CSS ID Selectors
- Authors
- Name
- Yevhenii Airapetian
- @airapetian_dev
One of a Kind: CSS ID Selectors by Y. Airapetian
Topic: CSS ID Selectors
Author: Y. Airapetian
Estimated Read Time: 16 mins
Contents:
1. Introduction
7. The Task
8. Extra Task 1
9. Extra Task 2
11. Summary
12. Useful Links
Introduction
You may ask: how is an ID selector any different from a tag or a class selector?
When we styled our tags by directly referring to their types, we wrote:
body{
background-color: #F0F8FF;
}
And when we wanted to differentiate some tag from others, or classify it, we wrote:
//HTML file
<h1 class="heading-main">Lorem ipsum dolor sat</h1>
//CSS file
.heading-main{
color: #778899;
}
We classified our heading to style it and style, e.g., any other level 1 heading that may be on our page.
CSS ID Selectors
Sometimes, however, we may need to change the appearance and behavior of an element that is one of a kind by its role.
For example, our code may have many paragraphs, spans, and level 6 headings, but only one main navigation. If this element won't be repeated in its function, meaning there's only one such tag with such semantic purpose, we can make use of an ID attribute in an HTML element:
//HTML file
<nav id="main-navigation">
//other tags here
</nav>
While an HTML element can have multiple values in a class attribute, like so:
//HTML file
<img class="img img-responsive img-post" src="./img/cat-pic.jpg" alt="A cat picture"/>
It can't have more than one value in an ID attribute:
//HTML file
//this will be incorrect
<nav id="main-navigation menu">
//other tags here
</nav>
This explains the name for this selector, ID, meaning identify something (make unique).
Note: If you feel confident in this topic and want to move on to the more advanced ones check out the post about responsive web design.
Or, if you need a refresher on how to use tag selectors and classes visit the tag and class selectors posts.
It doesn't prevent you from giving an element BOTH a class(es) and an ID value, like this:
//HTML file
<nav id="main-navigation" class="menu navbar navbar-nav">
//other tags here
</nav>
In fact, it is a common practice among web developers.
For an ID selector to work correctly, it needs to be:
- Start with a
hash (#)
sign. - After a
#
sign, there's an ID name which must begin with a letter(a-z, A-Z)
. - After the first letter (lowercase or uppercase), underscores
_
, hyphens-
and any letters are allowed. - The length of the ID name must be at least 1 character.
- The name cannot contain spaces.
- It must be unique to the document it is contained in.
Note: In HTML5 an ID name can start with any character (including a letter), though letter characters are advised for better compatibility.
So, these are proper ID names:
//proper names for an ID
<footer id="main-footer">
//other code here
</footer>
<footer id="FOOTER">
//other code here
</footer>
<footer id="footer-1">
//other code here
</footer>
And these are not:
//invalid names for an ID
<footer id="123">
//other code here
</footer>
<footer id="1footer">
//other code here
</footer>
<footer id="foo ter">
//other code here
</footer>
Take a look at an ID selector breakdown:
Figure 1.1: A breakdown of a CSS ID selector.
When we add an ID to a tag and style it, we say:
- Find me all elements that have an ID
navigation
; - If found, apply to the element(s) the properties/update the properties color, font-size and font-family with the values blue, 26px, and fantasy respectively.
Note 1: If no element is found, no styles will be applied.
Note 2: The ID selector is unique: it is meant to be used only once on a page. If you mark multiple elements with the same ID #nav
, the styles may apply to all of them, but you are relying on an unrecommended web development approach and risk getting broken styles in your app. Use classes instead whenever possible.
Note 3: Make sure you don't have a space in the ID names: It is not a class, hence, there's only one ID name (one complete sequence of characters).
Practical use cases
When should we use an ID selector? When:
1. We want to mark a tag to differentiate it from others on a page (make its purpose unique).
Practical use case: We'll usually have many textual-based tags in our markup (<a>, <span>, <p>
), but usually one navigation or footer. It makes sense to use IDs with these tags.
Figure 1.2: Working with IDs in HTML.
2. We want to create an anchor navigation in our app.
Practical use case: You surely have seen such behavior when using the web: a web page has a table of contents at the top and when you click on a certain link in it, it takes you to a specific section. This is done by using the <a>
tags whose href
attributes have values starting with a #
symbol. Also, you have a section you want the user to be taken to marked with an ID: the same that the previously mentioned <a>
tag has in the href
attribute (without the #
symbol).
//other code here
//navigation links on a page
<a href="#artists-19">
Artists of the 19th century
</a>
//other code here
//the section the user will be scrolled to
<div id="artists-19">
<p>This section will list the artists of the 19th century...</p>
<div>
By using other technologies like Javascript you can apply smooth transitions between pages/sections which look pretty nice. This method also works for quickly taking the user to the top (instead of manual scrolling)
Figure 1.3: An HTML anchor behavior.
3. When we design HTML forms.
Practical use case: It is common to use an ID with a label associated with an input field.
Figure 1.4: Working with IDs and HTML forms.
4. We use Javascript.
Practical use case: IDs are also commonly employed with Javascript, for example, when we want to use some dynamic behavior on a page or an event listener, such as a click. Since CSS is limited in terms of dynamic styling, this is a common use case for Javascript and IDs.
Figure 1.5: A page scroll behavior created with Javascript and IDs.
Naming best practices
You are safer when your ID name is:
1. Named semantic, meaning by the role the element performs:
<footer id="footer>
</footer>
<nav id="navigation">
</nav>
2. Consistent, meaning the one adhering to a single naming practice across the project (e.g. BEM).
#navigation{
}
#main-navigation{
}
#main-footer{
}
3. Short and descriptive names.
To recall what your code does after you stopped working on it a week or month ago, name the IDs as if you work with other programmers and they also need to know what this piece of code does. Otherwise you risk being like:
//not so apparent
.my-div{
}
//much better
.main-navigation{
}
4. Unique.
To remind you: IDs are designed to be used once on an HTML page.
5. Named without spaces.
To remind you: an ID is a single entity. Don't separate it with spaces.
//other code here
<div id="cont ainer">
//other code here
</div>
// other code here too
5. Named with the help of allowed characters.
Your code might work if you insert some rare symbol into your ID name. However, it may break at any time depending on different circumstances, like the Javascript modules you use or other reasons. To be on the safe side, give your IDs proper, memorable, and relevant names.
//risky code here
<div id="a&!?()app">
//other code here
</div>
// a more favorable name
<div id="app">
//other code here
</div>
Practice Makes Perfect
Reading is good, but practicing is even better! If you're ready to apply your newly gained skills in a little task, keep reading for the details.
Preparation Steps
Click on the button below to visit Code Sandbox. It's a coding playground we will use to practice our web dev skills.
You will see 3 windows:
Explorer
index.html
Preview
Figure 1.6: The CodeSandbox workspace.
If you're logged in, you probably already know what to do. But just in case, go to step 6.
If you're not logged it, you won't be able to edit the files. For this, you need to follow these steps:
- Click on the Sign in button. You can locate it to the top right of the screen.
Figure 1.7: The CodeSandbox workspace top navigation.
You will be offered a bunch of authorization methods. Click what best suits you but for the purposes of demonstration we'll stick with the Google authorization method.
- Click on Sign in with Google button.
Figure 1.8: The CodeSandbox authorization window.
You'll see a field where you need to write your email address.
Note: Here and afterwards the log in details have been partially shadowed due to the privacy reasons.
- Fill in your email address.
Figure 1.9: The Google authorization screen.
If successful, you'll see a password input filed.
- Fill in your password details.
Figure 1.10: The Google authorization screen.
If you've done this step, you might be prompted to confirm the login with your smartphone.
- Click to verify the authorization with your smartphone.
Figure 1.11: The Google authorization verification screen.
Then, click confirm on your smartphone. After, click continue or next in your browser if their's a respective pop-up window.
You should now be successfully authorized.
Note: Sometimes it gets buggy so you might have to refresh the CodeSandbox workspace.
If you're in, you can make a copy of the code to your CodeSandbox account.
- Click on the Fork button. You will find it to the top right of the screen.
Figure 1.13: The CodeSandbox workspace top navigation.
The code will be forked and you can start doing the task.
Note: Just as mentioned before, sometimes it gets buggy so you might need to reload the CodeSandbox workspace.
The Task
Figure 1.14: The done task.
We are interested in the central window marked with a green rectangle and the tab called HTML marked as well with a green rectangle.
Figure 1.15: The CodeSandbox workspace.
Here's a simple HTML page that was written for you to focus on practicing working with IDs.
It has a basic layout resembling a common-looking About Me page. Pay attention to the <a>
links at the top with the correspondingly named sections that follow after. At the bottom, there's one more link with the text To top.
Right now it looks like this:
Figure 1.16: Unstyled HTML page.
As you can see, when you click on a link, it reloads the page. It's a typical behavior of an HTML link without a value in the href
attribute.
Your task is to link the navigation links with the corresponding sections so that the pages behave like here:
Figure 1.17: Final result.
Step 1: While in the HTML file, add to each section an ID attribute and give it a value of the section's name.
Step 2: Go up to the navigation links and add to each link's href attribute a value so that when you click on a link it scrolls to the corresponding section.
Hint: If you're stuck, review the post's section where we discussed the common applications of IDs.
Step 3: Test that the feature is working. Click on all links. Do they scroll you to the sections? If yes:
Step 4: Do the same with the bottom link saying To top. Add an ID to some top element on the page, for example, the <h1>
tag.
Step 5: Finish by adding an anchor to the bottom link. It should scroll you to the main heading upon clicking it as in the GIF image above.
If you don't know how to complete a certain step, review the post's section about the common practices with the IDs. Also, feel free to use your Google search skills and research the topic.
You don't need to know everything at once and make it quickly or perfectly. The task is to get the feel of the topic and practice troubleshooting. Much of the time, developers work on fixing problems by using their troubleshooting skills which may involve, as you might have guessed, googling!
Extra Task 1:
If this task is too simple for you and you want to have extra practice in using IDs, here's another one!
Extra Step 1: Create an anchor navigation between HTML pages.
ES1.1: Create a new contact.html
page:
ES1.1.1: Click on the Create a new file icon in CodeSandbox and name it contact.html
as in the image:
Figure 1.18: Creating a new file in CodeSandbox.
ES1.1.2: Once in the new file, press on an exclamation mark !
on the keyboard and press the Tab key. The keyboard configurations vary so take your time if you don't know where a certain key is. On HP computers with a Windows system, for example, the exclamation mark is typed with Shift + 1
, and the Tab is located just under the 1
key to the top left.
Figure 1.19: A computer keyboard with some highlighted keys.
Once you've done it, you should get a generated HTML page skeleton.
Figure 1.20: Using a code editor shortcut.
If you don't understand what happened, don't worry! It's very simple: there are a bunch of shortcuts web developers use daily to save time and the shortcut ! + Tab
is one of them. It generates a minimal needed skeleton markup to start coding.
Note: We will cover shortcuts in web development in one of the future posts so stay tuned!
ES1.1.3: Just before the <title>
tag in the head
section of your document, insert this line of code:
<link rel="stylesheet" href="styles.css" />
By it, we're linking our contact.html
page with the styles.css
file. Then, give the page title a proper name, e.g. Contact. Inside the body tag, type another shortcut: p*8>Lorem
. It will generate 8 paragraphs with placeholder text.
Note 2: While using shortcuts is not encouraged in the early stages of learning web development, we do so to save time for practice preparation. Now, whenever possible, and if you still feel unsure of your skills, try to manually type the code.
ES1.1.4: Go back to the index.html
page and cut the section with the contact information at the bottom of the page. You can do this by highlighting the piece of code, right-clicking on it, and then clicking Cut
or by using the Ctrl + X
command (on Windows).
ES1.1.5: Place the cursor somewhere between the <p>
tags. Eight click, then click Paste
or use the Ctrl + V
command (on Windows).
ES1.1.6: After the last <p>
tag create a link tag <a>
and give it a text saying Back
;
ES1.1.7: Give the contact section a corresponding ID name. Go back to the index.html
page and put the proper value inside the contact <a>
tag's href
attribute.
Note 3: You may get stuck at this point as it may be a bit tricky to figure it out. Still, try to solve this on your own before Googling the answer.
ES1.1.8: Still in the index.html
page, give the <h1>
heading an ID, e.g. top
.
ES1.1.9: Finally, go back again to the contact.html
page and put inside the bottom Go Back link's href
attribute a proper anchor, just like in step 1.1.7.
ES1.1.10: Test your app. Does everything work as expected? Do the anchor links work? The result should be close to this:
Figure 1.21: Extra task 1 final result.
Extra Task 2:
Want to practice your styling skills? Let's make our web page more appealing.
Extra Step 1: Reset the default styles. Style the <body>
and <nav>
tags.
ES1.1: In your styles.css
file, type at the top:
*{
margin:0;
padding:0;
}
Note: When viewing our raw pages, they come with predefined styles depending on the browser that you use. To override this behavior (reset the styles), we use a *
selector - a universal selector. We will cover it in future posts, but right now you need to know it selects everything in our code.
ES1.1: Set the background image of the <body
tag to:
https://i.postimg.cc/jq4yJK47/R-1.jpg
ES1.2: Give the <nav>
a height of 80px;
ES1.3: Give the <nav>
a background-color of darkslategray;
ES1.4: Center the content of the <nav>
;
Extra Step 2: Style the <h1>
, <h2>
, and <h3>
tags.
ES2.1: Give the <h1>
a font-size of 24px and some top spacing;
ES2.2: Give the <h1>
a color of whitesmoke;
ES2.3: Remove the underline;
ES2.4: Give the <h2>
tag a font-size of 20px;
ES2.5: Give the <h2>
tag some top an left spacing;
ES2.6: Give the <h3>
tags some bottom spacing;
Extra Step 3: Style the profile picture <img>
tag.
ES3.1: Make the width of the <img>
smaller, for example 200px;
ES3.2: Center the <img>
on the page;
ES3.3: Give it a border and a border color;
Note: You can use a class for this substep.
Note 2: One way to center an image is to use margins with a display: block
property: value pair;
Note 3: A nice and simple image styling method is to make it round. To achieve this with the given image, use the border-radius
property with a value of 100px;
Extra Step 4: Style the <ul>
tag and its children.
ES4.1: Make the font size 18px;
ES4.2: Change the color of the font;
ES4.3: Remove the list markers and the underline;
ES4.4: Give some left and bottom spacing to the <ul>
tag;
ES4.5: Give some line-height
to the <ul>
tag;
Note: To style the <a>
tags inside the <li>
tags (or the <li>
tags inside the <ul>
tags), try to use a descendant selector like this:
ul li a{
//styles here
}
Note 2: This type of selector will be covered in future discussions.
Note 3: You can achieve pretty cool navigation styling effects by using the :hover
preudo class applied to the <a>
tags together with the transition property.
Extra Step 5: Style the <section>
tags and their children.
ES5.1: Make the font size 18px;
ES5.2: Change the color of the font;
ES5.3: Increase the line height;
ES5.4: Play with the sections' widths;
ES5.5: Give the <h3>
tags the same colors;
ES5.6: Make the projects smaller in size. Give them some spacing;
Note: To simplify the process, give the projects the same class name, e.g. projects;
ES5.7: Give some spacing to the <span>
tags and make them italic.
Note 2: One way to do this is to change the <span>
tags' display to block. To make it clean, give the spans a class name, e,g, cites. If you are not comfortable working with element positioning yet, skip this step.
ES5.8: Change the colors of the contact links. Make the cursor appear as a pointer when hovering over the contact links. Remove the underlines;
ES5.9: Give the sections some top, bottom, and left spacings;
Note 3: You can center the sections on the page by reducing their widths and applying auto margins to the left and right sides.
Extra Step 6: Style the <a>
tags at the bottom of the pages.
ES6.1: Make the font size 16px;
ES6.2: Change the hover behavior just like in the previous substep;
ES6.3: Fix this link to the bottom right of the page (when scrolling it stays where it is);
ES6.4: Remove the underline;
Note: Omit this step if you don't yet have enough skills in CSS positioning.
If you've done all the steps, congrats! The page should look similar to this:
Figure 1.22: The final result of the second Extra Exercise.
With a bit of styling our small project looks much more appealing!
Don't worry, though, if you failed to complete the task(s) from the first attempt. Read more in the Troubleshooting section that follows.
Troubleshooting steps
If you've tried to complete a certain step or a part of a step, but with no success, here's the basic troubleshooting process:
1. Ensure you're working in the right file (it should be an HTML one)
2. Ensure you've spelled the ID attribute and/or ID value right.
A proper ID attribute/value is:
<tag id="value">
<tag>
3. Ensure you've placed your ID attribute in the right tag.
4. Ensure you haven't forgotten to write/correctly spell an anchor in the href
attribute of a link tag.
5. Ensure you've hit Save
with the relevant keyboard command for the machine you're working on.
Summary
Yep, that was quite a day! In this post, we discussed what ID selectors are and when they are commonly used. We also touched upon how to name them properly and supported the newly gained knowledge with 2 practical tasks. Now give yourself some rest!
Keep up with your learning journey and I see you next time!
Y.A.