Element selector

Element selectors are the most basic type of selectors in CSS. They target HTML elements directly by their tag name. This allows you to style all elements of a specific type on your webpage.

Syntax

element_name {
  /* CSS properties and values */
}

Example

To style all paragraph elements on a page with a specific font, color, and size, you would use:

p {
  font-family: Arial, sans-serif;
  color: blue;
  font-size: 16px;
}

Commonly Used Element Selectors

  • p: Paragraph
  • h1, h2, h3, etc.: Headings
  • div: Division
  • span: Inline content
  • a: Anchor (link)
  • ul, ol, li: Unordered and Ordered Lists, List Items
  • table, tr, td, th: Table, Table Row, Table Data, Table Header

Styling Multiple Elements

You can style multiple elements at once by separating them with commas:

h1, h2, h3 {
  color: red;
  text-align: center;
}

Combining Element Selectors with Other Selectors

Element selectors can be combined with other selectors to create more specific styles. For example, you can combine them with class selectors or ID selectors:

#my-paragraph {
  /* Styles for the paragraph with the ID "my-paragraph" */
}

.important-text p {
  /* Styles for paragraphs within elements with the class "important-text" */
}

Key Points to Remember

  • Specificity: CSS rules are applied based on their specificity. More specific selectors (e.g., those with IDs) override less specific ones (e.g., those with only element selectors).
  • Cascading: CSS rules cascade, meaning that later rules can override earlier ones if they have equal or higher specificity.
  • Browser Compatibility: While most modern browsers support element selectors, it’s always a good practice to test your CSS across different browsers to ensure consistent styling.