html
/

CSS Selectors

Last Sync: Today

On this page

13
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

html

CSS Selectors

What are CSS Selectors?

CSS selectors are used to target HTML elements and apply styles to them.

Element Selector

CSSRead-only
1
p {
  color: blue;
}

Class Selector

CSSRead-only
1
.box {
  background: red;
}

ID Selector

CSSRead-only
1
#header {
  font-size: 20px;
}

Grouping Selector

CSSRead-only
1
h1, h2, p {
  color: green;
}

Universal Selector

CSSRead-only
1
* {
  margin: 0;
  padding: 0;
}

Attribute Selector

CSSRead-only
1
input[type="text"] {
  border: 1px solid #ccc;
}

Combinators

SelectorDescription
A BDescendant selector
A > BDirect child selector
A + BAdjacent sibling
A ~ BGeneral sibling

Pseudo-classes

CSSRead-only
1
a:hover {
  color: red;
}

Pseudo-elements

CSSRead-only
1
p::first-letter {
  font-size: 30px;
}

Best Practices

  • Use class selectors for reusable styles
  • Avoid overusing ID selectors
  • Keep selectors simple and readable
  • Use combinators carefully

Common Mistakes

  • Overly complex selectors
  • Using IDs instead of classes
  • Incorrect combinator usage
  • Not understanding specificity

Conclusion

CSS selectors are fundamental to applying styles. Mastering them helps create efficient and maintainable stylesheets.

Try it yourself

.box {
  background: blue;
}

#title {
  color: red;
}

Test Your Knowledge

Q1
of 3

Which selector targets class?

A
#
B
.
C
*
D
:
Q2
of 3

Which selector is unique?

A
class
B
id
C
element
D
group
Q3
of 3

Which selector targets all elements?

A
*
B
.
C
#
D
:

Frequently Asked Questions

What is a selector?

It targets HTML elements for styling.

Difference between class and ID?

Class can be reused, ID is unique.

What is pseudo-class?

It defines a special state like hover.

Previous

css syntax

Next

css comments

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.