DEV Community

wasifali
wasifali

Posted on

Why we add CSS and three ways to insert CSS

How To Add CSS

When a browser reads a style sheet, it will format the HTML document

Three Ways to Insert CSS

There are three ways of inserting a style sheet:
External CSS
Internal CSS
Inline CSS

External CSS

With an external style sheet, you can change the look of an entire website by changing just one file.

Example

External styles are defined within the <link> element, inside the <head> section of an HTML page:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="mystyle.css">
</head>
<body>

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

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Internal CSS

An internal style sheet may be used if one single HTML page has a unique style.

Example

Internal styles are defined within the <style> element, inside the <head> section of an HTML page:

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-color: linen;
}

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

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

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Inline CSS

An inline style may be used to apply a unique style for a single element.

Example

Inline styles are defined within the "style" attribute of the relevant element:

<!DOCTYPE html>
<html>
<body>

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

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Cascading Order

All the styles in a page will "cascade" into a new "virtual" style sheet by the following rules, where number one has the highest priority,
Inline style (inside an HTML element)
External and internal style sheets (in the head section)
Browser default

Multiple Style Sheets

If some properties have been defined for the same selector (element) in different style sheets, the value from the last read style sheet will be used.

Example

Assume that an external style sheet has the following style for the <h1> element:

h1 {
  color: navy;
}
Enter fullscreen mode Exit fullscreen mode

Then, assume that an internal style sheet also has the following style for the <h1> element:

h1 {
  color: orange;   
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)