Adding CSS (Cascading Style Sheets) to your HTML is essential for creating visually appealing and user-friendly web pages. In this guide, we will explore the three primary methods to link CSS to HTML documents: inline, internal, and external CSS. Each method has its advantages and best-use scenarios, helping you decide the best approach for your web development needs.
Methods to Link CSS to HTML
Note: It is a best practice to keep your CSS separate from your HTML
1. Inline CSS
Inline CSS allows you to apply styles directly within HTML tags using the style attribute. This method is useful for small-scale styling or when you need to apply a unique style to a single element.
Example: In this example, we will add CSS using inline styling.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Inline CSS</title>
</head>
<body>
<h2 style="color: green;">
Welcome to
<i style="color: green;">
GeeksforGeeks
</i>
</h2>
</body>
</html>
Output:
.png)
2. Internal CSS
Internal CSS involves adding CSS styles directly within the HTML file by including them inside the <style> tags. This method is more efficient for applying styles to a single HTML document and keeps your CSS code more organized compared to inline styling.
Note: It's best to add the <style> tags within the <head> section to ensure the styles are read before the body content is loaded.
Example: In this example, we will use the internal CSS approach for styling the web page.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Internal CSS</title>
<style>
h2 {
color: green;
}
</style>
</head>
<body>
<h2>Welcome to GeeksforGeeks</h2>
</body>
</html>
Output:
.png)
3. External CSS
External CSS involves creating a separate CSS file with a .css extension and linking it to the HTML file using the <link> tag. This method is the most efficient for large projects, as it separates the design from the content, allowing for better code maintainability and reusability.
Example of External CSS:
1. Create a file named styles.css:
CSS
h2 {
color: green;
font-size: 20px;
}
2. Link this CSS file in your HTML:
HTML
<!DOCTYPE html>
<html>
<head>
<title>External CSS</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h2>Welcome to GeeksforGeeks</h2>
</body>
</html>
Output:
.png)
Best Practices for Using CSS in HTML:
- Inline CSS:
- Best for small, unique styles on individual elements.
- Quick styling for one-time changes or testing.
- Applied directly to the HTML element using the
style
attribute.
- Internal CSS:
- Ideal for single-page websites or when styling a single document.
- Defined within the
<style>
tag in the <head>
section. - Easier to manage than inline CSS but still limited to one page.
- External CSS:
- Recommended for larger projects and multi-page websites.
- Provides better organization, maintainability, and reusability.
- Styles are defined in separate
.css
files and linked to the HTML through the <link>
tag.