How to Add CSS to Your HTML Document
Cascading Style Sheets (CSS) play a crucial role in web development by allowing you to control the visual presentation of your HTML documents. By styling your HTML elements with CSS, you can enhance the overall look and feel of your website. In this article, we’ll explore different methods of adding CSS to your HTML documents, along with examples.
Inline CSS
Inline CSS is the simplest way to apply styles directly to individual HTML elements. You can use the style
attribute within an HTML tag to define the styling. Here’s an example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inline CSS Example</title>
</head>
<body>
<h1 style="color: blue; text-align: center;">Welcome to My Website</h1>
<p style="font-size: 16px; line-height: 1.5;">This is a paragraph with inline CSS styling.</p>
</body>
</html>
In this example, the style
attribute is used to set the text color and alignment of the heading (<h1>
) and the font size and line height of the paragraph (<p>
).
Internal (or Embedded) CSS
Internal or embedded CSS involves placing your styles within a <style>
tag in the <head>
section of your HTML document. This method is useful when you want to apply styles to multiple elements across your page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Internal CSS Example</title>
<style>
h1 {
color: green;
text-align: center;
}
p {
font-size: 18px;
line-height: 1.6;
}
</style>
</head>
<body>
<h1>Welcome to My Website</h1>
<p>This is a paragraph with internal CSS styling.</p>
</body>
</html>
In this example, styles for the <h1>
and <p>
elements are defined within the <style>
tag in the <head>
section.
External CSS
External CSS involves creating a separate CSS file and linking it to your HTML document. This method is ideal for maintaining a clean and organized code structure.
styles.css:
/* styles.css */
h1 {
color: purple;
text-align: center;
}
p {
font-size: 20px;
line-height: 1.8;
}
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>External CSS Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Welcome to My Website</h1>
<p>This is a paragraph with external CSS styling.</p>
</body>
</html>
In this example, the styles are kept in a separate file named styles.css
, and the HTML file links to this external stylesheet using the <link>
tag.
Choose the method that best suits your project’s needs, and start enhancing the visual appeal of your HTML documents with CSS!