Home /Blog/ CSS Selectors: Class and ID basic filtering for HTML elements

Code, CSS, HTML

CSS Selectors: Class and ID basic filtering for HTML elements

We’ve seen the basics of selectors.CSS selectors offer versatile ways to target specific HTML elements for styling. While we’ve covered basic tag selectors, let’s delve into class and id selectors, showcasing their syntax and usage.

Class Selectors

To target elements with a specific class, use the class selector syntax: .class {}. Here’s an example:

HTML:

<p class="dog-name">Roger</p>

CSS:

.dog-name {
  color: yellow;
}
<p class="dog-name">Roger</p>

Repeating Classes vs. Unique IDs

  • Repeating Classes: You can repeat the same class value across multiple elements within an HTML document. For example, several elements can share the class “dog-name.”
  • Unique IDs: An id must be unique within an HTML document. It can only be used once. For instance, an id like “dog-name” should be assigned to a single element.

ID Selectors

To target elements with a specific id, use the id selector syntax: #id {}. Here’s an example:

HTML:

<p id="dog-name">Roger</p>

CSS:

#dog-name {
  color: yellow;
}

Understanding the nuances of class and id selectors provides you with powerful tools for styling specific elements or groups of elements within your HTML documents. As you progress, you’ll discover more advanced selectors and techniques to enhance your CSS styling capabilities. Stay tuned for further exploration into the world of CSS.

Raman Singh

Raman is a digital marketing expert with over 8 years of experience. He has a deep understanding of various digital marketing strategies, including affiliate marketing. His expertise lies in technical SEO, where he leverages his skills to optimize websites for search engines and drive organic traffic. Raman is passionate about staying up-to-date with the latest industry trends and sharing his knowledge to help businesses succeed in the online world.