Skip to main content

How to Write a CSS Rule

CSS, which stands for Cascading Style Sheets, is a language used to describe the look and formatting of a document written in HTML. In this article, we'll walk through the process of writing a basic CSS rule.

Understanding CSS Rules

A CSS rule is a set of styling instructions for a specific HTML element or group of elements. A CSS rule consists of a selector and a declaration block.

The selector points to the HTML element you want to style. The declaration block contains one or more declarations separated by semicolons. Each declaration includes a CSS property name and a value, separated by a colon.

Here's the structure of a CSS rule:

selector {
property: value;
}

For example, to style all paragraph (<p>) elements with the color red, we'd write the following CSS rule:

p {
color: red;
}

Writing Your First CSS Rule

Let's write a CSS rule together. We'll start by selecting an HTML element. For this example, we'll use the <h1> element. The selector for our rule will be h1.

Next, we'll choose a property to change. Let's change the color of the text. The property for this is color.

Finally, we'll choose a value for our property. We'll make the text blue, so our value will be blue.

Here's our CSS rule:

h1 {
color: blue;
}

Applying Multiple Styles

To apply more than one style to an element, simply add more declarations to your declaration block. For example, let's make our <h1> text blue and center it on the page. We'll need to use the text-align property in addition to color.

Here's our new CSS rule:

h1 {
color: blue;
text-align: center;
}

Each declaration is separated by a semicolon.

Conclusion

Writing a CSS rule is as simple as knowing which element you want to style, what you want to change about it, and how you want to change it. Remember the format: selector {property: value;}. With these basics, you can start to explore the vast possibilities of CSS. Happy styling!