MyInternships.in

CSS Tutorial

CSS Selectors

Selectors are how you tell CSS which HTML elements to style. Mastering selectors is the key to controlling exactly what changes on your page.


What is a selector?

A CSS selector is the part of a rule that decides which elements the styling applies to. Choose the wrong selector and nothing changes, or the wrong thing changes. There are several types, and each targets elements in a different way.

Element selector

The element (or type) selector matches all elements of a given tag name. For example, "p" selects every paragraph on the page.

Selects all paragraphs
p {
  color: green;
}

Id selector

The id selector targets one unique element with a specific id. In CSS you write a hash (#) followed by the id name. An id should be used only once per page.

Selects the element with id="intro"
#intro {
  font-weight: bold;
}

Class selector

The class selector targets all elements with a given class. In CSS you write a dot (.) followed by the class name. Unlike ids, a class can be reused on many elements, which makes classes the most popular selector.

Selects every element with class="highlight"
.highlight {
  background-color: yellow;
}

Try selectors in action

Element, id and class selectors together
Example
<!DOCTYPE html>
<html>
<head>
<style>
  p {
    color: #333;
  }
  #main-title {
    color: navy;
    text-align: center;
  }
  .note {
    background-color: #fff3cd;
    padding: 8px;
    border-left: 4px solid #ffb400;
  }
</style>
</head>
<body>
  <h1 id="main-title">CSS Selectors</h1>
  <p>This is a normal paragraph.</p>
  <p class="note">This paragraph uses the .note class.</p>
</body>
</html>

Universal and grouping selectors

The universal selector (*) selects every element on the page. The grouping selector lets you apply the same styles to several selectors at once by separating them with commas.

Universal and grouping
* {
  margin: 0;
}

h1, h2, h3 {
  color: teal;
}

Common selectors summary

SelectorSyntaxSelects
ElementpAll <p> elements
Id#introThe element with id="intro"
Class.boxAll elements with class="box"
Universal*Every element
Groupingh1, h2All <h1> and <h2> elements
💡

Prefer classes over ids for styling. Classes are reusable, and it keeps your CSS flexible when your page grows.

Key points

  • Selectors decide which elements get styled.
  • Element selectors use the tag name (p, h1).
  • Id selectors use # and should be unique.
  • Class selectors use . and can be reused.
  • * selects everything; commas group selectors.

Related CSS Topics

Keep learning with these closely related tutorials.

Ready to use your CSS skills?

Find web development internships and fresher jobs across India.

Browse Web Dev Internships