In this CSS tutorial, you will learn how to add CSS styles in your HTML document.
There are three different ways to add CSS in your HTML documents:
- Inline CSS – Directly inserting a
<style>
attribute in the starting of the HTML tag. - Internal CSS – Adding
<style>
tag in the head section of the document. - External CSS – Using the
<link>
tag to include externally defined styles in the document.
Let’s discuss each method in detail:
1. Inline CSS
Inline CSS is mostly used when we want to apply a unique style on a single HTML element only.
To add inline CSS, we have to insert a style attribute in the starting of the HTML tag. This style attribute can take any number of CSS property: value;
pairs, where each property: value;
pair must be separated by a semicolon(;
). Refer to the example below:
Example:
<!DOCTYPE html> <html> <body> <h1 style="color: red; background-color: yellow;">This is the main heading</h1> <h2 style="color: blue; background-color: gold;">This is a sub heading</h2> <p style="border: 5px solid cyan;padding: 10px">This is a paragraph.</p> </body> </html>
2. Internal CSS
Internal CSS is used when we want to apply some unique styles to a single page or document only. Such styles only affect the page or document where they are embedded in.
The internal CSS is written inside the <style>
tag, within the <head>
section of the document. You can define any number of styles within the <style>
tag. Refer to the example below:
Example:
<!DOCTYPE html> <html> <head> <style> body { background-color: gold; } h1 { color: red; text-decoration: underline; } p{ border: 5px solid green; padding: 10px; } </style> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph.</p> </body> </html>
3. External CSS
External CSS is used when we want to apply some common styles to multiple pages or sections of a website. One common example is the footer of the website, which looks exactly the same across all pages of the website.
To create external CSS, you have to first create a CSS file with a .css
extension. Write all your styles inside this CSS file. After writing all CSS styles, include this CSS file in the <head>
section of the document using a <link>
tag. Refer to the example below:
Example:
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="demo.css"> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph.</p> </body> </html>
Below is how the ‘demo.css’ file looks:
‘demo.css’
body { background-color: gold; } h1 { color: red; text-decoration: underline; } p{ border: 5px solid green; padding: 10px; }