Ids vs. Classes in HTML

Ids and classes are ways to identify specific elements within an html document. This can allow you to apply certain CSS to specific elements or add functionality using JavaScript to those elements.

Within one html document/file or one webpage there can only be one element with a unique Id. Every element can have it’s own Id, but they all most be unique. However, classes do not have to be unique, multiple elements can share the same class. The below code shows a two paragraph elements, each have their own unique Id, but they both share the ‘para’ class. The first paragraph element also has the ‘top-para’ class. Multiple classes can be applied to a single element, but each element can only have one id.

The below code snippet shows how to use ids and classes within CSS. The cSS shows applying style to sections of a document using element selector, id selectors, and class selectors. The css is currently within a style tag, inside the head tag, we could externalise the css into it’s own file. Externalising css can allow you to apply the same stylesheet to multiple html pages.

By just specifying the element tag name we can apply styles to every element of that tag type within a html document. The below code sets the ‘padding’ attribute to all paragraph elements within a html document.

The below code snippet sets the ‘font-size’ of an element that has the id of ‘para1’. The id selector within a stylesheet must be prefixed with the hashtag ‘#’ symbol.

Using the dot ‘.’ prefix we can apply styles to all elements that have a certain class. The below code snippet sets the background colour and text colour of all elements that have the class ‘para’.

Remember, within one html document of file each id must be unique, two elements cannot share the same id, but multiple elements can share the same class name. You can also apply multiple classes to one element but an element can only have one id.

Leave a Reply