DEV Community

Jaisurya
Jaisurya

Posted on • Edited on

CSS Selectors

Here are the four foundational selectors you'll use 90% of the time.

1. The Universal Selector ( * )

This selects everything on the HTML page.

* {
  margin: 0;
  box-sizing: border-box;
}

Enter fullscreen mode Exit fullscreen mode

2. The Type Selector ( element )

HTML tags matching the name directly. This is best for setting baseline styles for paragraphs, headings, or buttons.

p {
  color: #333;
  line-height: 1.5;
}

Enter fullscreen mode Exit fullscreen mode

3. The Class Selector ( .class )

Any element with a matching class attribute. Uses a dot ( . ).
This is best for reusable styles you want to apply to multiple different elements.

.btn-primary {
  background: blue;
  color: white;
}

HTML: <button class="btn-primary">Click</button>
Enter fullscreen mode Exit fullscreen mode

4. The ID Selector ( #id )

A single element with a matching id attribute. Uses a hashtag ( # ).Unique, one-of-a-kind elements on a page (like a specific sidebar or nav).

#main-header {
  background: black;
}

HTML: <header id="main-header">...</header>
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
topstar_ai profile image
Luis Cruz

I appreciate how you've broken down the foundational selectors into four clear categories, making it easy to understand their distinct use cases. I've found the Class Selector to be particularly useful for creating reusable styles, as it allows for a lot of flexibility when working with multiple elements. In my experience, it's also important to consider the specificity of selectors when combining them, to avoid unintended styling conflicts. Do you have any advice on how to balance specificity with the need for reusable, modular CSS code?

Collapse
 
jaisurya profile image
Jaisurya

Thanks for your appreciation! You can use single class selectors rather than id selectors to make the CSS code reusable and modular.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.