Sign in
Log inSign up

Using Class and ID in HTML

Motunrayo Sanni's photo
Motunrayo Sanni
·Jan 30, 2022·

2 min read

Selectors allow you to target specific elements on a web page that you can apply styles to. The class selector can be used to style multiple elements. ID, on the other hand, applies a style to one unique element.

ID selectors are defined by using a hash (#) sign then immediately followed by the ID value that you want to apply the style to in CSS. This selector can only be used to style one element. This means that ID selector can never be used to style more than one element. For example, as displayed below:

WhatsApp Image 2022-01-30 at 5.51.40 PM.jpeg The ID for this element can only be used for this element.

The class selector is not unique to an element. A class selector can be used across multiple elements. Class selectors are defined by using a period (.) sign then immediately followed by the class name that you want to apply the style to in CSS. So, if you apply a style to multiple elements, those elements will have the same styles applied to them. An example is shown below:

WhatsApp Image 2022-01-30 at 5.51.39 PM (1).jpeg

In HTML, you can apply a class and an ID selector to an element. For example:

WhatsApp Image 2022-01-30 at 5.51.39 PM (2).jpeg

The h1 and h2 tags will be subject to the styles for the class "heading". In addition, the tags will also use the styles applied to the given ID's.

Unlike classes whose only function is only to apply styles to elements, ID has multiple functions. One of those functions is to use the ID selector to link a part of a page.

WhatsApp Image 2022-01-30 at 5.51.39 PM.jpeg

In this example, a certain part of the page is given an ID so, when you get to the footer of the page, you can just click on the link to take you back to that part of the page.

And yeah, I hope this was explanatory enough. Thank you.

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct