There are two parts to a CSS rule: Selectors and Declarations. The selector references the HTML element that you want to style, and the declaration is the style that you want to apply to that element. Declarations have two parts as well: a property and a value.

Example 1:

The CSS rule in Example 1 sets the text color of all h1 elements to the color red.

Selectors

HTML elements referenced by selectors can be done in a number of ways, including:

  • The tag name, such as p, h1, nav, footer, main, etc..
  • Class selectors which include a period (.) as a prefix to the class name such as .center-text. Classes are used to identify a category or a group of elements that will be styled similarly.
  • ID selectors which include a hashtag symbol (#) as a prefix to the ID such as #main-title. Id is used to identify unique elments.
  • Both a tag name and a class can be used as a selector to reference all elements of the selected tag with that specific class. For example a CSS rule with the selector p.center-text references the HTML elements with the p tag but only those with the class center-text as well.
  • If multiple selectors will be styled similarly, we can group them together by separating them with a comma (,). We can group different tags, classes, and id on the same line.

Declarations

A declaration is the style that you want to apply to the HTML element referenced by the selectors. Declarations have two parts: a property followed by a colon (:) and a space, and a value followed by a semicolon (;). For example, if we need to center the text of an element, text-align is the property and the value will be center.
Moreover, we can have multiple declarations in the same block that sits between the curly brackets.

Comments

It is good practice to add comments to your CSS to explain what it does, and to make your code easier for others to read and understand.
The comments start with /* and end with */. The browser will not interpret anything between these characters either it is one line or multiple lines of comments.

Lesson 2 Example

The following example covers all the concepts we mentioned above:

  • Selectors as tags
  • Selectors as a class name
  • Selectors as an ID
  • Selector as a tag+class
  • Multiple grouped selectors
  • Single declaration
  • Multiple declarations
  • Single line comments
  • multi-line comments

Practice Lesson 2

Try this example with JSFiddle!

LEAVE A REPLY

Please enter your comment!
Please enter your name here