CSS Basics

CSS Rule

A CSS declaration has parts, a selector and a rule.

h1 {
    color: red;
}

The first part is the selector, in this case we are selecting all h1 tags. It is followed by 2 curly braces. Inside the curly braces are the rules or styles we want to apply.

Where do we make our styles?

There are 3 ways we can make our styles:

  • Internal styles
  • Inline styles (bad practice)
  • External styles (best practice)
Internal styles
<html>
    <head>
        <title>Example</title>
        <style>
            h1 {
                color: red;
            }            
        </style>
    </head>
    <body>
        <h1>Example</h1>
    </body>
</html>
Inline styles
<html>
    <head>
        <title>Example</title>
    </head>
    <body>
        <h1 style='color: red;'>Example</h1>
    </body>
</html>
External styles
<html>
    <head>
        <title>Example</title>
        <link rel="stylesheet" href="./css/styles.css">
    </head>
    <body>
        <h1>Example</h1>
    </body>
</html>
h1 {
    color: red;
}
<html>
    <head>
        <title>Example</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css" />
    </head>
    <body>
        <h1>Example</h1>
    </body>
</html>

CSS Selectors

Element Selectors

This selector selects all tags on your page and styles them

h1 {
    color: red;
}

p {
    color: red;
}
<h1>Styled Heder</h1>
<p>Styled Paragraph</p>
ID Selectors

This selector selects the element with that id and styles it. Id's are meant to only appear once on each page.

#app {
    color: red;
}
<div id='app'>
    <p>Example Text</p>
</div>
Class Selectors

This selector selects all elements with that class and styles it. Classes are more flexible because they can be used more than once on a page. This makes them the most common selector to use.

.card {
    color: red;
}
<div class='card'>
    <p>Example Text</p>
</div>
Using multiple selectors

If we want to style multiple selectors at a time, we type them all out, separated by a comma, and then write our styles.

.card, .article {
    color: red;
}
<div class='card'>
    <p>Example Text</p>
</div>

<div class='article'>
    <p>Example Text</p>
</div>
Selecting children of an element

There are times when we want to select a paragraph tag inside a certain element, we do it by typing them both out, but instead of a comma separating the two, we just have a space.

.card p {
    color: red;
}
<div class='card'>
    <p>Styled text</p>
</div>

<div class='article'>
    <p>Not styled text</p>
</div>
The Universal Selector

This will style every element on your page.

* {
    color: red;
}

results matching ""

    No results matching ""