There are several ways to add CSS to your HTML documents:
- Inline CSS: You can add CSS directly to an HTML element using the
style
attribute. For example:
<p style="color: red;">This paragraph is red.</p>
Inline CSS is not recommended for larger stylesheets as it can make the HTML code harder to read and maintain.
- Internal CSS: You can add CSS to an HTML document using the
<style>
element inside the<head>
section of the HTML document. For example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<style>
p {
color: red;
}
</style>
</head>
<body>
<p>This paragraph is red.</p>
</body>
</html>
This method is useful for small stylesheets that are specific to a single HTML document.
- External CSS: You can add CSS to an HTML document by linking to an external CSS file using the
<link>
element inside the<head>
section of the HTML document. For example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<p>This paragraph is styled by the styles.css file.</p>
</body>
</html>
This method is recommended for larger stylesheets or stylesheets that are used across multiple HTML documents.
In the external CSS method, you need to create a separate CSS file (e.g., styles.css
) with your CSS rules. For example:
p {
color: red;
}
You can then link to this CSS file from your HTML document using the <link>
element, as shown above.
Note that the order of your CSS rules matter, and that styles added later will override styles added earlier. It’s also important to use good naming conventions for your classes and IDs to make your CSS code easier to read and maintain.