How to Add CSS (Inclusion Methods)

How to Add CSS (Inclusion Methods)

There are three ways of inserting a style sheet into an HTML document: Inline, Internal, and External.

1. External CSS

This is the most professional and common method. All your styles are written in a separate file with a .css extension, and you link it in the <head> section of your HTML.

  • Pros: You can change the look of an entire website by changing just one file.
  • Extension: Must be saved as .css (e.g., style.css).

The HTML (index.html):

<head>
  <link rel="stylesheet" href="style.css">
</head>

The CSS (style.css):

body {
  background-color: lightblue;
}
h1 {
  color: navy;
  margin-left: 20px;
}

2. Internal CSS

Internal styles are used when a single HTML page has a unique style. You define the styles inside the <style> element, which is placed inside the <head> section.

The HTML:

<head>
<style>
  body {
    background-color: linen;
  }
  h1 {
    color: maroon;
    margin-left: 40px;
  }
</style>
</head>

Attributes of the <style> Element

When using Internal CSS, the <style> tag can take several attributes that define how the browser handles the code:

AttributeDescription
mediaSpecifies which media/device the style is for (e.g., media="print" or media="screen").
typeDefines the styling language. Usually text/css. (Optional in HTML5).
titleProvides a name for the style sheet (often used for alternate stylesheets).
nonceA cryptographic number used to allow-list styles in a Content Security Policy (Security feature).

3. Inline CSS

Inline styles are used to apply a unique style to a single element. To use inline styles, add the style attribute directly to the relevant tag.

  • Note: This method is generally avoided as it mixes content with presentation.

The HTML:

<h1 style="color:blue; text-align:center;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>

4. The @import Rule

The @import rule allows you to import one style sheet into another style sheet. This is useful for keeping your CSS modular or importing Google Fonts.

The Syntax:

It must be at the very top of your CSS file.

@import url("navigation.css");
@import url("https://fonts.googleapis.com/css?family=Sofia");

body {
  font-family: 'Sofia', sans-serif;
}

Example using the media attribute:

<style media="print">
  body { font-size: 12pt; color: black; }
  .navbar { display: none; } /* Hide navigation on paper */
</style>

Cascading Order: Which one wins?

If an HTML element is styled by more than one method, they will “cascade” into a new virtual style sheet by the following rules (where number 1 has the highest priority):

  1. Inline style (inside an HTML element)
  2. External and Internal style sheets (in the head section)
  3. Browser default