CSS in HTML

Cascading Style Sheets (CSS) are used to describe the presentation of HTML documents. CSS may be used to control page background color, font size, style, element sizes, etc. 

You can add CSS to HTML in three main ways:

  • Inline style sheets - defines styles directly in the element it is affecting using the style attribute. Inline styles have the highest priority compared with the other modes of adding style sheets. Example:
<div>
    <p style="color:green;font-size:14px">This text is green</p>
    <p style="color:red;font-size:18px">This is a red text with bigger font</p>
</div>

Output:

This text is green

This is a red text with bigger font

  • Internal style sheets - defines styles within the head element of the HTML document. The style can attach directly to element names or class and id attributes of elements. This way of adding styles has the next highest priority after inline styles. Example:
<!DOCTYPE html> 
<html>
    <head> 
        <style type="text/css">
            p {
                color: red
            }
            .test-paragraph-1 {
                font-style: italic
            }
            .test-paragraph-2 {
                font-weight: bold
            }
        </style>
    </head>
        <body>
            <div>
                <p class"test-paragraph-1">This text is the first paragraph</p>
                <p class="test-paragraph-2">This text is the second paragraph</p>
            </div>
        </body>
</html>

Output:

This text is the first paragraph

This text is the second paragraph

  • External style sheets - this type of style sheet can be attached to multiple HTML pages via a link. As the name suggests, an external style sheet is defined in a separate file from the HTML document(s). This type of style sheet has the lowest priority.

Example: let's create a CSS file custom_style.css. Within this file, let us define our styles:

 p {
     color: red
 }
 .test-paragraph-1 {
     font-style: italic
 }
 .test-paragraph-2 {
     font-weight: bold
 }

Now, let us create an HTML dicument that links to the CSS file we have created above.

<!DOCTYPE html> 
<html>
    <head> 
        <link rel = "stylesheet" type = "text/css" href = "custom_style.css">
    </head>
        <body>
            <div>
                <p class"test-paragraph-1">This text is the first paragraph</p>
                <p class="test-paragraph-2">This text is the second paragraph</p>
            </div>
        </body>
</html>

Output will be exactly the same as the output on the internal style sheets:

This text is the first paragraph

This text is the second paragraph