How to Add CSS in HTML?
- CSS stands for Cascading Style Sheets.
- CSS is used to style and design HTML web pages.
- CSS controls colors, fonts, spacing, layouts, and animations of websites.
- CSS can be added to HTML documents in three different ways.
- The three methods are Inline CSS, Internal CSS, and External CSS.
What is CSS?
CSS (Cascading Style Sheets) is a stylesheet language used to describe how HTML elements should be displayed on a webpage. While HTML creates the structure of a webpage, CSS makes it attractive by adding colors, layouts, fonts, and responsive designs.
CSS works together with HTML to create modern websites. Without CSS, web pages would appear as plain text without proper styling.
Ways to Add CSS in HTML
There are three common ways to add CSS styles to an HTML document:
1. Inline CSS
CSS is written directly inside the HTML element using the
style attribute.
2. Internal CSS
CSS is written inside the
<style>
tag in the HTML document's
<head>
section.
3. External CSS
CSS is written in a separate file and connected with HTML using
the
<link>
tag.
1. Adding Inline CSS in HTML
Inline CSS is used to apply styles to a single HTML element.
The CSS code is written inside the style attribute.
<h1 style="color: blue;">
Welcome to CSS
</h1>
Welcome to CSS
2. Adding Internal CSS in HTML
Internal CSS is added inside the
<style>
element placed in the
<head>
section of HTML.
<html>
<head>
<style>
h1 {
color: green;
}
</style>
</head>
<body>
<h1>
Internal CSS Example
</h1>
</body>
</html>
3. Adding External CSS in HTML
External CSS is the most commonly used method in professional websites.
CSS code is stored in a separate file with the
.css
extension.
The CSS file is connected to HTML using the
<link>
element.
<head>
<link
rel="stylesheet"
href="style.css"
>
</head>
Creating an External CSS File
Create a file named style.css and write your CSS code inside it.
body {
background-color: lightgray;
}
h1
{
color: blue;
}
Difference Between Inline, Internal and External CSS
| CSS Type | Where Used | Best For |
|---|---|---|
| Inline CSS | Inside HTML element | Small changes |
| Internal CSS | Inside <style> tag | Single page styling |
| External CSS | Separate CSS file | Large websites |
Which Method Should You Use?
For learning and small examples, Inline and Internal CSS can be useful. However, professional developers usually prefer External CSS because it:
- Keeps HTML and CSS separate.
- Makes code cleaner and easier to manage.
- Allows multiple pages to use the same stylesheet.
- Improves website maintenance.
- Helps create scalable websites.
Conclusion
CSS can be added to HTML using three methods: Inline CSS, Internal CSS, and External CSS. Among these methods, External CSS is the preferred approach for modern web development because it provides better organization and reusability.