Cascading Style Sheets

Methods for including CSS

Cascading Style Sheets(CSS) is a stylesheet language that is used for providing presentational or stylistic information on HTML elements. The browser uses the CSS rules defined by the web page author for displaying the elements. There are three ways for including CSS rules in HTML pages.

  • Using the style attribute
  • Using the style element
  • Linking to an external file using a link element

The format of a CSS rule


selector{

property:value;

property:value;

}

Here selector represents an HTML element, the property represents a CSS property and the value represents a proper CSS value.

Style element

The style element is used for defining CSS rules that will be applied to the rest of the web page. All the CSS rules are enclosed by the style element. It is usually present inside the head element. This is also known as Internal CSS.


<style>
p {
color: white;
background-color: green;
}

</style>

The link element is used for linking to an external CSS file that has the CSS rules for the web page. The external CSS file usually has a .css extension. Multiple web pages can link to the same stylesheet file. This makes changing the styles easier since we have to change in only one location. Then the change will be made for all the web pages. Since the link element is an empty element, it requires no closing tag. This method is also known as external CSS.

<link rel="stylesheet" href="example.css">

In this the example.css has to be in the same folder as the web page for this line to work.

What does Cascading in CSS mean?

The cascading part of CSS means that styles can be overridden. Generally, the CSS rule which is most nearer to the element will be applied. The order of cascading is:

  • Style attribute
  • Style element or link element(Based on which comes last)
  • Browser stylesheet

In case of any user-defined stylesheets being not present, the browser applies its own set of CSS rules.

Example web page


<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>Cascading Style Sheets</title>
<style>
p {
color: white;
background-color: green;
}

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

<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>

</html>


h1 {
color: white;
background-color: blue;
}