Episode 13 of 53

Targeting Multiple Elements

Learn how to apply the same styles to multiple elements using grouped selectors.

Often you want several elements to share the same styles. Instead of writing duplicate rules, you can group selectors with a comma.

Grouped Selectors

/* Without grouping — repetitive */
h1 { color: #2c3e50; font-family: Georgia, serif; }
h2 { color: #2c3e50; font-family: Georgia, serif; }
h3 { color: #2c3e50; font-family: Georgia, serif; }

/* With grouping — clean and DRY */
h1, h2, h3 {
    color: #2c3e50;
    font-family: Georgia, serif;
}

Mixing Selector Types

You can group any types of selectors together:

h1, .subtitle, #intro {
    text-align: center;
    margin-bottom: 1rem;
}

Best Practices

  • Put each selector on its own line for readability
  • Group only when elements truly share the same styles
  • You can still add individual rules for unique styles
/* Shared styles */
h1,
h2,
h3 {
    font-family: Georgia, serif;
    color: #2c3e50;
}

/* Individual styles */
h1 { font-size: 2.5rem; }
h2 { font-size: 2rem; }
h3 { font-size: 1.5rem; }