Learn to Code: Episode 012 – CSS Basics

Now it’s time to discuss CSS finally! All websites must have HTML. Whereas CSS (Cascading Style Sheet) is optional but essential in any website. We can only do so much with HTML alone. CSS makes web pages become lively.

There are three ways to add a style into a web page:

  1. Linked stylesheet file
  2. Inline stylesheet
  3. Embedded stylesheet

Linked Stylesheet

In this method, the CSS is defined on a separate file and then linked to a web page using the <link> element. The attributes needed are rel (relationship of the linked file to the HTML file) set to "stylesheet" and the href attribute which is set to the path pointing to the actual stylesheet file.

The syntax for adding CSS this way is:

selector {
property-name: value;
}

We’ll talk more about selectors on the future episodes but the basic ones are the HTML elements, classes, and id attributes.

Inline Stylesheet

The CSS is added to the style attribute of the element directly. Here is an example:

<p style="color:blue;">My content</p>

So it’s basically the same as linked stylesheet but without the selector due to obvious reason.

Embedded Stylesheet

Instead of creating a separate CSS file, embedded stylesheet uses the <style> element inside the <head> element of the HTML. Here is an example:

<head>
<title>Sample</title>
<style>
p {
color: orange;
}
</style>
</head>

Which method should be used?

Once the HTML and CSS gets more complicated and more of them is added, it will become very difficult to maintain inline and embedded stylesheets. Therefore, as early as possible, use the linked stylesheet even if your HTML and CSS are still very simple. Here are the benefits:

  • Separation of concerns
  • Better collaboration – you can assign someone else to work on the CSS or vice versa.
  • Better tooling support

Please check out the video below to see CSS in action using some basic properties and selectors. See you in the next episode!

Leave a Reply

Your email address will not be published. Required fields are marked *