MakeW3web

Types of selectors

Here are the types of selectors in CSS, explained in simple terms with examples:

1. Element selectors - An element selector targets HTML elements by their name, such as `p`, `h1`, `div`, etc. When you use an element selector, the style rules you define will be applied to all instances of that element in your document.

Example:

p {
  font-size: 16px;
  color: #333;
}

This will apply the font size of 16 pixels and color of #333 to all `p` elements on your website.

2. Class selectors -A class selector targets HTML elements that have a specific class attribute. You can apply the same class to multiple elements, and then style them all at once using the class selector.

Example:

.intro {
  font-size: 24px;
  color: #666;
}

In this example, we are selecting all elements with the class attribute "intro" and applying a font size of 24 pixels and color of #666.

3. ID selectors - An ID selector targets a specific HTML element based on its unique `id` attribute. An ID should only be used once per document, so an ID selector will only apply to one element.

Example:

#main-heading {
  font-size: 36px;
  color: #000;
}

In this example, we are selecting the element with the ID attribute "main-heading" and applying a font size of 36 pixels and color of #000.

4. Attribute selectors - An attribute selector targets HTML elements based on their attributes, such as `href`, `src`, `alt`, etc. You can use different comparison operators to specify the exact attribute value you want to target.

Example:

a[target="_blank"] {
  color: #f00;
}

In this example, we are selecting all anchor tags (`a` elements) that have a `target` attribute with a value of `_blank` and applying a color of #f00 to them.

5. Pseudo-class selectors - A pseudo-class selector targets elements based on their state, such as `:hover`, `:active`, `:visited`, etc. Pseudo-classes are used to add interactivity and dynamic effects to your styles.

Example:

a:hover {
  text-decoration: underline;
}

In this example, we are selecting all anchor tags that are being hovered over (`:hover` state) and applying an underline text decoration to them.

6. Pseudo-element selectors - A pseudo-element selector targets a specific part of an element, such as the first letter, or the content before or after an element. Pseudo-elements are used to add decorative or structural elements to your styles.

Example:

p::first-letter {
  font-size: 24px;
  font-weight: bold;
}

In this example, we are selecting the first letter of all `p` elements and applying a font size of 24 pixels and bold font weight to them.

Was this page helpful?