GETTING STARTED WITH CSS


CSS can be used to add styling to a webpage. CSS file is basically a file stored with the .css extension.

Here are the three methods of including CSS in an HTML file:


Inline Styles


  • Inline styles are very efficient because they allow you to apply various style rules to a component by adding the CSS rules into any start tag.
  • The style attribute consists of a sequence of CSS property and value pairs, we can separate "property: value" by using a semicolon ( ; )
  • Usage of inline styles is basically a bad practice.
  • The presentation becomes mixed with the content of document because style rules are embedded directly within the HTML tag.

Example:


<!DOCTYPE html>
<html>
<head>
<title>Playing with Inline Styles</title>
</head>
<body>
<p style="color:green;font-size:34px;">
  I'm a paragraph with inline styling
</p>
</body>
</html>

Live Demo!


Output:

I'm a paragraph with inline styling



EMBEDDED STYLE SHEETS


  • Internal style sheets only affect the document in which they are embedded.
  • These are defined in the <head> portion of an HTML file using the <style> tag.
  • You can define multiple <style> components in an HTML document but they must be in between the <head> and </head> tags.

Example:


<!DOCTYPE html>
<html>
<head>
<style>
  p {
   color: pink;
  }
  h1 {
    color: brown;
    margin: 5px;
  }
</style>
</head>
<body>

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

</body>
</html>

Live Demo!


Output:

This is a heading

This is a paragraph



External Style Sheets


An external stylesheet is the ideal approach when we need to apply styling to multiple pages.

External style sheet has all the CSS rules in a seperate file so that it can be linked from any html file in the site.

Before linking, we need to create a style sheet. Let's create a new file named style.css, and put the following code into it:

style.css


body {
  background: green;
  font-size: 18px;
}
h1 {
  color: red;
}



Now we need to link it to our HTML document. We can use the <link> tag, which goes inside the <head> section.



<!DOCTYPE html>
<html lang="en">
<head>
<title>My HTML Document</title>
<link rel="stylesheet" href="externalstyle.css">
</head>
<body>

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

</body>
</html>

Live Demo!


Output:

This is a heading

This is a paragraph of text.