Skip to content

Week 3_2(en): CSS Rule Structure and Selectors

njs03332 edited this page Jul 23, 2018 · 10 revisions

CSS Rule Structure and Selectors

Now let's learn the syntax of CSS!

CSS Rule Structure

css rule structure
This is how a typical CSS rule looks like.

  • Selector: indicates the part we are going to apply the style to
  • Declaration Block: within the {}, specify how we want to style the part we selected
  • Declaration: consisted of property and its value in the form of property: value;
  • We can have as many declarations inside a rule as we like.

Different Types of Selectors

CSS can select HTML elements by tag, class, or ID.
Let's learn about each of them.

  1. Tag Selector As we did earlier, we can use a tag name as a selector to apply the style to all the elements of that name on our page.
    We already have a rule for the <h1> tag. Let's modify the rule and add another one for the <p> tag.
h1 {
  color: red;
  font-size: 30px;
  text-align: center;
}

p {
  font-size: 20px;
  font-family: Arial;
}

You will see that the rule is applied to every <p> element.

  1. Class Selector CSS is not limited to selecting elements by tag name.
    HTML elements can have more than just a tag name. They can also have attributes!
    One common element is the class attribute, which we used last time.
    We've learned that the class attribute can be used to style our page in a consistent way.
    Let's add the following code to our blog.css file.
.south-korea {
  text-transform: uppercase;
  color: blueviolet;
}

To select an HTML element by its class, a period must come in front of the class name.

It is possible to add more than one class name to an HTML element's class attribute.
For example, let's say we want to make the title of our article darkgreen and bold.
We can add two rules like below.

.darkgreen {
  color: darkgreen;
}

.bold {
  font-weight: bold;
}

Then, we can include both of these classes to a single element.

<h2 class="darkgreen bold">...</h2>

Like this, we can add multiple classes to an element's class attribute by separating them with a space.
This prevents us from writing a custom class for every style combination needed, and enables us to mix and match CSS classes to create many unique styles.

  1. ID Selector
Clone this wiki locally