Classes and IDs

Elements

Elements, classes and IDs are all examples of selectors in CSS. Elements were covered in the last lesson; they cover all the HTML tags and are a useful and easy way to change elements in a mass array. It is usually used to change the fonts and colours of a certain type of text (h1, h2, p, etc.). The example below demonstrates changing all h1's, h2's and p's to the colour, red, and the font, arial.

Classes

The most common and useful selector is the 'class' selector. The class selector lets users select HTML elements based on their class attribute and it is used with CSS to distinguish elements for their own styling. In order to link an element to a class, you need to put 'class="className"' after the element, still within the brackets. Then, in your CSS document, type '.className'. The dot before the class name lets the document know that you are referencing to a class and the class name lets the document know what class you are talking about. An example is shown below, with the HTML document on the left and the CSS document on the right.

Classes can be used across multiple webpages, with different elements, multiple times, and this is what makes classes much better as compared to IDs.

IDs

Even though IDs do the same job as classes, it is clearly inferior as an ID can only be used once for one specific element, as compared to classes which can do multiple elements across multiple pages. In order to link an element to an ID, you need to put 'id="idName"' after the element, still within the brackets. Then, in your CSS document, type '#idName'. The hashtag before the ID name lets the document know that you are referencing to an ID and the ID name lets the document know what ID you are talking about. An example is shown below, with the HTML document on the left and the CSS document on the right.











Activity 1

In the textboxes below, the left being an HTML document and the right being a CSS document, add a class to the h1, h2, h3, h5 and h6 elements. Name the class 'normalHeading'. Then add an ID to the h4 element and name the ID: 'strangeHeading'. In the CSS document, make the elements within the class: 'normalHeading', change the font to Arial and the colour to blue. Make the element linked to the ID: 'strangeHeading', have the font: 'fantasy' and change the colour to cyan. Change the background colour of the body to #556b2f.















©{{CodeIt}}School 2023