0
0
CssHow-ToBeginner · 3 min read

How to Use Element Selector in CSS: Simple Guide

The element selector in CSS targets all HTML elements of a specific type by using the element's tag name directly in the CSS rule. For example, p { color: blue; } styles all paragraph tags with blue text.
📐

Syntax

The element selector uses the HTML tag name to select all elements of that type on the page.

  • element: The HTML tag name you want to style (e.g., p, h1, div).
  • { ... }: Curly braces contain the CSS properties and values to apply.
css
element {
  property: value;
}
💻

Example

This example styles all h2 headings with green text and all p paragraphs with gray text and a larger font size.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Element Selector Example</title>
<style>
h2 {
  color: green;
}
p {
  color: gray;
  font-size: 1.2rem;
}
</style>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph styled with the element selector.</p>
<p>All paragraphs get the same style.</p>
</body>
</html>
Output
A webpage showing a green heading 'This is a heading' and two paragraphs in gray color with slightly larger text.
⚠️

Common Pitfalls

One common mistake is confusing element selectors with class or ID selectors. Element selectors target all tags of that type, so if you want to style only specific elements, use classes or IDs instead.

Another pitfall is forgetting that element selectors apply globally, which can cause unintended styling on many elements.

css
/* Wrong: Trying to select a class with element selector */
.my-paragraph {
  color: red;
}

/* Right: Use class selector for specific elements */
.my-paragraph {
  color: red;
}
📊

Quick Reference

Use element selectors to style all elements of a certain tag. Combine with other selectors for more control.

  • p - selects all paragraphs
  • h1 - selects all main headings
  • div - selects all div containers

Remember: element selectors are simple and powerful but affect every matching tag.

Key Takeaways

Element selectors target all HTML tags of a given type by using the tag name in CSS.
They apply styles globally to every matching element on the page.
Use element selectors for broad styling and combine with classes or IDs for specific control.
Syntax is simple: write the tag name followed by curly braces with CSS rules inside.
Avoid confusing element selectors with class or ID selectors to prevent unwanted styling.