Using the <style> tag, you can add styles for a single HTML document. These are internal styles. They will be applied to all content on the page. But only one page.

In practice, you will create hundreds of HTML documents and use the same styles in them. For example, paragraphs or headings are usually styled the same way. It would be very convenient to add styles once for all similar pages.

Imagine you are creating your blog. All post pages should be styled the same.

<!DOCTYPE html>
<html>
  <head>
<title> My personal blog </title>
  </head>
  <body>
    <h1> Post about learning HTML and CSS </h1>
    <h6> Date of publication: 20.12.2020 </h6>
    <p> I really like learning HTML layouts! </p>
  </body>
</html>

I’m sure you can easily add styles to the <h1>, <h6> and <p> elements on the page using internal styles. But our goal today is to create styles that can be used on other pages as well.

Headlines and paragraphs should look the same on all blog pages.

— Probably we need to move all these styles into a separate file?

— That’s right, all styles are placed in a separate file with the extension .css. You can call it whatever you like. The name styles.css is a very common one.

The rules for writing styles in it are exactly the same as for styles in the <style> tag:

  • first, we specify the name of the tag
  • then in curly braces, we list all CSS properties with values

Let’s start by aligning all <h1> headings to the center of the page. To do this, you can use the CSS property text-align, with the value center.

Let’s create a file styles.css and add 3 lines to it:

h1 {
  text-align: center;
}

Linking external styles

After creating the styles.css file, it needs to be linked to the HTML document.

Let’s imagine the following structure of documents on our site:

|-- my-blog
    |-- post-1.html
    |-- styles.css

To link the styles.css file to the post-1.html file, we need a single <link> tag.

Styles are always placed inside the <head> container.

To link the CSS file properly, we need to perform several actions with the <link> tag:

  • add the attribute type with the value text/css

  • add the attribute rel (relationship) with the value stylesheet

  • add the attribute href to indicate the path to the stylesheet

This is how post-1.html will look once we link the styles from styles.css:

<!DOCTYPE html>
<html>
  <head>
<title> My personal blog </title>
    <link rel="stylesheet" type="text/css" href="./styles.css">
  </head>
  <body>
    <h1> Post about learning HTML and CSS </h1>
    <h6> Date of publication: 20.12.2020 </h6>
    <p> I think I'm making amazing progress in learning layout </p>
  </body>
</html>

Even if you have one page, it is still better to use external styles. This way, you can slightly reduce the size and speed up the loading of the HTML document.