Classes & IDs

In this section we're going to build upon the work we did with divs and spans, by learning all about classes and IDs. We be learning what they are, and how we apply them to elements, and also we use them to target elements that we will then do something with, predominantly using CSS or JavaScript.

We’ll have a bit of exposure to CSS in this section. I’m not expecting you to get CSS down right now. But now is a good time to begin introducing it to you, a little at a time, to show its not difficult at all to pick up.

So you’ll see some in action and hopefully, this early exposure will be beneficial when we are ready to move on to CSS fully.

A QUICK LOOK AT CSS SYNTAX

I’ll start by talking about CSS syntax. The CSS element selector is simply the name of the element and then the styles we want inside of curly braces.

So here, every single div will be styled like so - red border and text, pinkish background and a margin to create some space around each div.

A class selector looks similar to the element selector, but it’s a name - any name that we choose. It is totally up to us what we call our classes - and they are preceded by a full stop or period (.).

An ID selector is a name of our choosing preceded by a hash symbol (“#”). Here’s a comparison of the three.

I don’t want you to worry too much about CSS syntax right now, as we’ll cover selectors in depth shortly in the upcoming CSS section, but I wanted to show you these selectors so that you know that periods (.) represent classes and hash symbols (#) represent IDs.

So we’re interested in the name, and a hash or dot in front of it. The reason, is that we can use this same syntax with Emmet in our HTML files to quickly write elements with classes and IDs attached.

OVER TO VS CODE So, I’ll highlight and copy the CSS, the link to this is below if you want to do the same, and paste it into my own CSS file and save. I just have an empty CSS file here, and an HTML file with the boilerplate built out using Emmet’s shortcut of hitting the exclamation mark and hitting tab. We’ll go to the HTML, and if I put p+p in the body, by now we know what will happen. Emmet gives us this abbreviation window that indicates that as things stand, we’re going to create two sibling paragraph elements. If i change to p.green+p, using the css syntax for a class, we see in the window here, that the first p element now has this class attribute, and if i put p.green+p#bold, the second p has an id attribute.
If we hit tab, Emmet makes two paragraphs one with the class of green applied and one with the ID of bold. I’ll also give each paragraph 10 words of lorem ipsum and save and there we go. Two paragraphs that are simply styled, one with a class and one with an ID.
So, once Emmet makes the elements in HTML, we see that the syntax for classes and IDs is different. Classes and IDs are simply denoted in HTML by keywords and they go in the opening tags of the elements they are applied to. This should be familiar now, as this is just like all of the other attributes we have been learning about.
Classes and IDs have the same syntax of a keyword, an equals sign, and then the value goes in the quotations. In this case, the value of green for the class or bold for id means that any styles associated with green or with bold would be applied to these particular elements respectively. In our case our .green class is just making the text green and our #bold id is making the text in that paragraph bold.
ID & CLASS DEFINITION So from what we’ve seen, we can say that classes and IDs are a way for us to target specific HTML elements so that we can do something with them - like apply styles. We can also use IDs and classes to target HTML elements with JavaScript, and we’ll look at a simple examples in a bit.
ID & CLASS DIFFERENCES IDs and classes do have differences. An ID is used to identify one element uniquely. So an ID can only be used one time in an html file. This can be on a div, or a paragraph or whatever you like. But you must use it only once to identify an element uniquely. A class on the other hand can be used on multiple elements wherever you want throughout a page. 100,000 times if you really wanted, though that would of course be silly.
CODEPEN DIVS & SPANS - https://codepen.io/craigcodes/pen/gyVmEB In the last lecture, as we saw earlier, we applied some styles to divs and spans by selecting the elements directly.
This approach is perfectly fine, but it wouldn’t necessarily always meet our needs, as here we are selecting and styling every div or every span on the page. Maybe we only want to style specific divs or spans or other elements, and this is where classes and IDs come in. They help us to target only the element or elements that have the given class or ID.
So, I’m going to work in this same file that we had at the end of the last video. If you want to code along the link to this code is in the description. You can either grab it from the GitHub repo or work within this Codepen. Up to you. If you work in the codepen, make sure you click this button to fork (FORK IT) it so you can save your changes.
Also, I’m going to write the classes & IDs manually for the remainder of this video, I suggest you do too, so you can get used to the syntax. So, inside my first div here I'm going to say we have an attribute called class which is equal to double quotes.
Inside the double quotes we give some kind of value - in this case, the class name. I’ll give it the value of ‘list’, as this is descriptive of what we have here. Where possible, it is good practice to have class and ID names that describe what they are doing or what they are being used for.
So, I’m going to use this list class to make a huge series of changes to how the list in this div appears. I don’t expect you to follow along with the CSS, as I haven’t taught it yet. But the CSS will help demonstrate classes and IDs.
So in the CSS, this will be .list and curly braces. So i’ll have border: none, and save, and we see that removes the red border, i’ll make the color of the text content white, i’ll give it a dark grey background colour, say #333 - which is a hexadecimal color code and we’ll have a series of lectures on color in CSS that goes over the various ways to colour our pages. Then we’ll give some space in our nav bar by adding some padding.
SPECIFICITY Though the previous div styles are still being applied to all the divs on the page, including the div that the .list class is applied to, they are now being overridden by the styles we’ve just added. This is due to a CSS rule called called specificity. We will talk about this fully in the upcoming CSS section of videos, but very briefly, class selectors are more specific than element selectors in CSS. So when an element has styles applied to it from more than one selector, styles that come from a class will take precedence over styles applied directly to elements.
There are of course styles which will take precedence over class selectors. If you want to dive into some more information on this right now then head over to this link at CSS Tricks https://css-tricks.com/specifics-on-css-specificity/ which explains the concept really beautifully. I won’t spend too long on this right now, but i will draw attention quickly to this image, which gives us a simplified guide to specificity in CSS. We see that styles applied directly to elements are the least specific. The most specific is the style attribute, or we would call this inline styles applied directly in the opening tag of the element. There is actually a higher specificity than this, and the highest specificity comes from the !important declaration, which overrides everything else, and we can see this here on MDN https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity#The_!important_exception. It says, “When an important rule is used on a style declaration, this declaration overrides any other declarations … however, it is bad practice and should be avoided because it makes debugging more difficult by breaking the natural cascading in your stylesheets.”
BACK TO THE CODE But ok, back to the code. Next I want to target the list that’s inside the div. For that we use a descendant combinator of .list ul. This is saying target any ul element that is a descendant of an element with the class of .list. We do this as we have another ul on the page in the ‘Our products’ section, and that ul is not a descendant of an element with the class of list at the moment, so will be unaffected by these styles. If we just said ul by itself here, then it would be affected.
FLEXBOX So for these styles we’ll use some flexbox to lay out the list. Flexbox was designed to help us with layout, space distribution between items and also gives us better alignment capabilities. Again, we’ll cover flexbox in some depth during the CSS section of videos and we’ll build out some cool projects with it.
For now, as we’re just focusing on HTML, I’ll refrain from explaining it and just go ahead and get to work. We’ll set the ul element to be a flex container using the display: flex property and we’ll justify the content to the end of the flex-container.
Next, we’ll target the actual list items. First we’ll take away these bullet points that are given to us by default using list-style: none. Then we’ll space them out a little using some padding.
Ok, so we’re getting there. Hopefully, you’re beginning to get an idea of the workflow used in CSS, where we burrow down into elements and use the specificity concept to target their children.
The very last thing we need to do is to have something happen when we hover one of the list items, which is fairly typical in navigation bars or clickable elements on the page. We need to give some indication to our users that a given element is interactive.
So for this i’ll use the hover pseudo-class, which again i’ll explain during the CSS videos. But briefly, we use a pseudo-class to define a special state of an element - like when it is being hovered, or when a link has been previously clicked on etc.
HOVER & PSEUDO ELEMENTS So we’ll have .list li:hover. Here, we’re saying for any li element that is a descendant of an element with the class of list, when it is hovered over do what is in this block, or what’s inside these curly braces. So in this case, i’ll say that on hover, change the text color to yellow, and make the cursor a pointer rather than an arrow.
Ok, so if we try that we see those changes. That’s looking a lot better, and remember we have achieved these wholesale changes by applying just one class that’s just applied to the div that contains the ul.
USE A CLASS MORE THAN ONCE ON THE PAGE We can use classes as many times as we like on the page. So let’s use the .list class again. If we pop down to where the HTML for the ‘Our Products’ section is, let’s add it to the div that’s wrapping everything. We automatically, have this huge style transformation from a single class attribute being added.
BOOTSTRAP If you’ve heard of Bootstrap https://getbootstrap.com/, which is a UI framework, then what we’ve just done is a simplified version of the concept behind how Bootstrap works.
(click get started) Bootstrap is essentially a huge stylesheet and a huge JavaScript file, that you just add a link to in your HTML file. Bootstrap is a huge amount of styles that are pre-written for you, and you just add their classes to your HTML elements. You can find a list of those classes here: https://www.w3schools.com/bootstrap/bootstrap_ref_all_classes.asp.
Once you add one or more of those classes, you will see an instant stylistic change, as we did when we added the .list class to the our products section. We see that one class name results in a huge change in style, and now we have two div elements that point to the same class name in the CSS file.
MULTIPLE CLASSES, ONE ELEMENT In addition to using a single class across multiple elements, we can also use more than one class on a single element. Class names are separated by a space when we do this. We just add the class attribute keyword once, and all class names inside the quotation marks, separated from existing classes by a space.
So in the ‘Our Products’ section, i’m going to add a second class of .green-text, making sure it is separated from the .list class by a space. Then i’ll head over to the CSS, and add .green-text and give it the color of springgreen. Now we see that this second class has added that color to the text of the element it is applied to.
DIFFERENT ELEMENTS We don’t just have to apply our classes to divs and style everything within them as we have done so far. Different types of element can share a class. We’ll give the first list item in the top div the class of .green-text also, and we see that the list item takes on that style, and the other list items remain as they were.
So you can apply a class to whatever HTML element you like and classes can be used simultaneously as many times as you like on the page, on whatever combination of elements you want them applied to.
JAVASCRIPT Also, as I said earlier, we can also use classes to target elements for use with JavaScript and i’ll give you a very quick and simple example. The goal isn’t to understand the CSS or JS i’m writing, so I’m trying not to explain it too deeply, I’m just trying to give a good demonstration of how we use classes and IDs in the real world, so when you see them in markup you’re looking at, you’ll know why they’re there.
So i’ll give our only h1 a class of .main-heading, and, I can make use of this with JavaScript. I’ll show you a simple example of triggering an alert popup when we click on the heading. So i’ll select the main-heading class that we applied to the h1 (pause). Then we’ll add an event listener which is listening for some event to happen on the page. A click, or when a mouse passes over an element for example. And we’ll say we’ll listen for a click, and on click we’ll call a function, which will alert “You clicked the heading!”
Now if we save, head over to the h1 and click, we see that we can trigger the alert. We could do way more than this with JS, and we will do all in good time. We could use this same technique to click through a carousel of images, or click a button to show particular items on the page and hide others, we could hover an image to show a larger version, or click an internal link to trigger a scroll to another section of the page, and so on.
Again, the goal isn’t to explain the JavaScript, we’re just demonstrating the use of the class. What i’m trying to highlight throughout, which i hope you’re getting, is that we have a class in our HTML, we targeted the element the class is applied to and we are then doing something with it. We can have more than one class on an element, and multiple instances of the same class throughout our web page.
IDs Ok cool, so let’s look at IDs. IDs do differ from classes but can also have similar applications. I’ll add an ID to the top div. So we’ll add the id keyword and equals sign and the quotation marks, and we’ll call this ID ‘top’.
Next, I’m going to go to the CSS and if we remember, IDs are denoted by a hash symbol or octothorpe. So we’ll say #top, the curly braces and then we’ll add the styles inside these. We’ll just add a border and it will be 3px solid and springgreen again.
OUTER CONTAINER ID Next I’m going to place all of our content inside of an outer container so we can control the width the page content takes up, as well as the alignment. So I’m going to highlight all of our content and cut it. Create a div with the id of outer-container, and for this we can use the Emmet shortcut of #outer-container, and Emmet will automatically assume it is being applied to a div if we don’t specify the element. For other elements, you would add the element name in front of the id. If we hit tab it creates the div and then we just paste all of our content inside.
Now in the CSS, we’ll add our id selector for the outer-container. Inside the curly braces we’ll set the width of the container and therefore all of the content inside to 80%. So it will take up 80% of the page width, and we’ll align it centrally using the margin 0 auto trick.
So we see that like classes, we can style elements using IDs. We’ve styled two different divs in different ways using IDs.
When we talked about classes we discovered that we could use the same class multiple times across the page. We can’t do that with IDs as these are unique identifiers. Our IDs we have applied are defining unique characteristics of our page here. Namely, the outer container all of our content is in - there can be only one outer container. Secondly the top of the page. We can only have one top of the page. So that’s really the main difference between classes and IDs - An HTML element can only have one unique id that belongs to that single element, while a class name can be used by multiple elements:
INTERNAL LINKS There are reasons we want our IDs be unique and only occur once. One reason is navigation within a page. We can use the top ID that we created to navigate to the top of the page. You will have see those buttons on websites that say something like ‘Go back to the top’. Well these are done using internal links, which make use of IDs. I’ll show you how.
So if we go to the bottom of the page and create an a element and in the href, we just reference that ID using #top. We’ll give it some text content we can click that says ‘Back to the top’.
Now we save and got to the bottom of the page and we see our internal link here. We could of course style this to look like a button of some sort, but i’ll leave that for now as we’re just looking at the functionality.
So we have the href set to the id of top, and that id references the top div which is the navigation. So If we click our link, it should take us to the top of the page, and there we go. I won’t do all of these nav links, but we’ll add an href of #contact here, and in the contact section, we’ll add the id of contact to the div that is wrapping the form. Now if we test that, we have two working internal links that we’ve made using IDs. And its this behaviour which makes it clear to us why we need our IDs to be unique. Once we have added an internal link, using an ID as an href, then the browser needs to know where to relocate to on the page.
We have looked at these internal links previously and even added some JavaScript to add some nice smooth scrolling, so if you haven’t seen that and want to find out more, check that out in the link appearing now (ADD CARD https://www.youtube.com/watch?v=DaCn8a_RouI), or use the link that i’ll provide below in the description. In fact, i’ll add this github gist https://gist.github.com/craigbourne/53c4d695abd8fdde76c301c7c8f68e9d in the description too and if i take this code and pop it into the javascript, with a comment to say ‘scrolling’ just so you know waht it is, we now have this nice scrolling effect on our internal links.
JAVASCRIPT Again, we can use IDs with JavaScript in a similar way to how we saw with Classes. We can grab hold of IDs using the getElementById method. So to speed things up i’ll copy what we did to trigger the alert for the click on the heading and make some modifications. So we’ll have a variable of contact, we’ll getElementById this time and we’re getting the ID of ‘contact’.
Then we’ll add an event listener to contact and this time instead of triggering an alert, we’ll change the color of the background of the div the contact form is in when its clicked. We’ll change it to our lovely spring green color. So we’ll put contact.style.backgroundColor = ‘springgreen’.
So, we’ve selected the element with the ID of contact and saved it to a variable. We’re then adding an event listener to that variable to listen for a click. When there is a click, we’re saying change the color of the background to spring green.
So let’s test that out, and we see it works nicely. So that’s how we grab an ID with JavaScript, We have seen how we do it with the CSS ID selector, and we know that we need them to be unique, occurring once on the page for identification purposes for things like internal linking and for labels to be bound to form inputs etc etc We have used IDs with forms in a previous video, so I won’t demonstrate that here, (SHOW EXAMPLE - https://codepen.io/craigcodes/pen/YMvVrm).
but you can check out how we were doing that in that video, which i’ll link in the description or it is in the card that is popping up on the screen now (ADD CARD - ).
Ok, so that has been classes and IDs and I hope you now have a deep and detailed understanding of why and how they’re used in front end web development. They really allow us to marry together the three core front end languages. We can target specific HTML elements so that we can do something with them - like apply styles or use JavaScript. We can have more than one class on an element, and multiple instances of the same class throughout our web page. IDs are unique on the page and must not be repeated. We can use IDs for purposes of internal linking and binding labels to form inputs, and we can also use them to style elements

FURTHER RESOURCES

GITHUB REPO USED IN THE VIDEO

Next section →