askvity

What are the different parts of a CSS style rule?

Published in CSS Basics 3 mins read

A CSS style rule has two main parts: the selector and the declaration. These two parts work together to tell the browser which HTML elements to style and how to style them.

Understanding the CSS Rule Structure

A CSS rule specifies how an HTML element should be displayed. Let's break down its components:

1. Selector

  • The selector targets the HTML elements you want to style. It identifies the element(s) in the HTML document that the rule will be applied to.
  • Common selectors include:
    • Element Selectors: Target HTML elements directly by their name (e.g., h1, p, div). The reference mentions that element names are case-insensitive, so h1 and H1 are equivalent.
    • Class Selectors: Target elements with a specific class attribute (e.g., .my-class).
    • ID Selectors: Target an element with a unique ID attribute (e.g., #my-id).
    • Attribute Selectors: Target elements based on their attributes (e.g., a[href]).
    • Combinator Selectors: Target elements based on their relationships to other elements (e.g., div p - selects all <p> elements inside <div> elements).

2. Declaration

  • The declaration specifies the styles to be applied to the selected elements. It contains two parts:
    • Property: The CSS property you want to change (e.g., color, font-size, background-color).
    • Value: The value you want to assign to the property (e.g., red, 16px, blue).
  • Declarations are always enclosed within curly braces {} and separated by a colon : between the property and value. Multiple declarations can be included within the braces, separated by semicolons ;.

Example

h1 {
  color: red;
  font-size: 24px;
}

In this example:

  • h1 is the selector, targeting all <h1> elements.
  • { color: red; font-size: 24px; } is the declaration, setting the text color to red and the font size to 24 pixels.

Summary in Table Format

Part Description Example
Selector Identifies the HTML element(s) to be styled. h1, .my-class, #my-id, a[href]
Declaration Specifies the styling rules to apply to the selected element(s). { color: red; font-size: 24px; }
Property The style attribute you want to change. color, font-size, background-color
Value The specific value assigned to a style property. red, 16px, blue, Arial

In essence, the selector chooses which element to style, and the declaration explains how to style it by setting property-value pairs within curly braces. This structure is fundamental to understanding and writing effective CSS.

Related Articles