CSS for Web Development

0% completed

Previous
Next
ID Selectors

CSS ID selectors let you style a unique element on your web page. They are used by adding an id attribute to an HTML element. An ID selector applies styles only to the element with the matching id value. This method is useful when you want to style a single item differently from the rest of the page.

Unlike class selectors, ID selectors should be unique within a page, which means you should use an id only once per HTML document.

Syntax

Follow below syntax to add an ID selector in CSS code.

#selector { property: value; }

Explanation:

  • #selector:
    • #: Indicates that the selector is an ID.
    • selector: This is the name of the ID that matches the element's id attribute.
  • property: The feature of the element you want to style (e.g., color, margin).
  • value: The setting for that property (e.g., green, 15px).

Example 1: Basic ID Selector

In this example, we will style an element with a unique id called unique-header. The example changes the text color and adds extra space below the element.

HTML

. . . .

Explanation:

  • ID Selector for #unique-header:
    • Selector Usage: The rule targets the element that has id="unique-header".
    • Style Rules:
      • Color: The text color is set to dark green.
      • Margin Bottom: A margin of 20 pixels is added beneath the header.
  • Outcome: Only the <h1> element with the specified ID will receive the styles.

Example 2: Combining ID Selector with Other Elements

In this example, we will demonstrate how an ID selector can be used alongside element selectors. The ID is used to style a unique paragraph differently than other paragraphs on the page.

HTML

. . . .

Explanation:

  • General Paragraph Styling:
    • Selector: The p element targets all paragraphs.
    • Styles: All paragraphs get gray text and 16px font size.
  • Unique ID Styling for #special-paragraph:
    • Selector: The ID selector #special-paragraph applies only to the paragraph with that ID.
    • Styles: This paragraph gets maroon text and bold font weight.
  • Outcome:
    • General Rule: All paragraphs have a common style unless overridden.
    • ID Rule: The paragraph with the specific ID is uniquely styled, overriding the general paragraph styling where applicable.

This lesson shows how to use ID selectors to target a specific element. You now understand how to apply unique styles to HTML elements using their id attribute.

.....

.....

.....

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