CSS for Web Development

0% completed

Previous
Next
Grouping and Combining Simple Selectors

Grouping and combining selectors let you apply the same style to different elements. This method makes your CSS shorter and easier to maintain. You can group selectors to share common properties or combine them to target elements based on multiple conditions.

Using grouping means you can write one rule for many selectors. Combining simple selectors means you can target elements that meet several criteria at the same time.

Syntax

Follow below syntax to group and combine simple selectors in CSS code.

selector1, selector2, selector3 { property: value; }

Explanation:

  • selector1, selector2, selector3:
    • Selector Grouping: Multiple selectors are separated by commas. The rule applies to all listed elements.
  • property: The style attribute you want to change (e.g., color, margin).
  • value: The new value for that attribute (e.g., blue, 10px).

When combining selectors without commas, you target elements that meet all criteria. For example:

element.class { property: value; }

Explanation:

  • element.class:
    • Combined Selector: This targets only the given element that also has the specified class.
  • property & value: Set the desired style accordingly.

Example 1: Grouping Element Selectors

In this example, we will group multiple element selectors to apply the same style to them. The example applies a shared color and font family to headers and paragraphs.

HTML

. . . .

Explanation:

  • Grouped Selectors:
    • h1, p: The rule applies to both header and paragraph elements.
  • Properties Applied:
    • Color: Sets a common text color for consistency.
    • Font Family: Applies the same font to keep design unified.
  • Outcome: Both <h1> and <p> are styled identically as defined.

Example 2: Combining Element and Class Selectors

In this example, we will combine an element selector with a class selector. The example targets only list items within a list that have a specific class.

HTML

. . . .

Explanation:

  • Combined Selector:
    • li.active: Targets only <li> elements that include the class "active".
  • Properties Applied:
    • Background Color: Highlights the active items with a distinct background.
    • Font Weight: Emphasizes the active items by making text bold.
  • Outcome:
    • Active List Items: Only list items with the "active" class receive the combined style, while other list items retain the standard style.

This lesson demonstrates how to group selectors to apply the same style to different elements and combine selectors to target specific elements that meet multiple conditions. These techniques simplify your CSS and help you create a more organized and efficient style sheet.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next