Introduction
In this chapter, you will learn about HTML styles, which are used to apply formatting and design to HTML elements. By using styles, you can control the appearance of your web pages, making them more visually appealing and user-friendly. This chapter covers inline styles, internal styles, and external stylesheets.
What are HTML Styles?
HTML styles allow you to apply CSS (Cascading Style Sheets) rules to HTML elements. CSS is a language used to describe the presentation of a web page, including colors, fonts, and layout. Styles can be applied in three ways: inline, internal, and external.
Inline Styles
Inline styles are applied directly within an HTML element’s start tag using the style
attribute.
Syntax
<element style="property: value;">
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inline Styles</title>
</head>
<body>
<h1 style="color: blue;">This is a blue heading</h1>
<p style="font-size: 20px; color: red;">This is a red paragraph with larger text.</p>
</body>
</html>
Internal Styles
Internal styles are defined within the <style>
tag inside the <head>
section of an HTML document. This method is useful for applying styles to a single HTML document.
Syntax
<head>
<style>
selector {
property: value;
}
</style>
</head>
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Internal Styles</title>
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
color: green;
}
p {
font-size: 18px;
color: purple;
}
</style>
</head>
<body>
<h1>This is a green heading</h1>
<p>This is a purple paragraph with larger text.</p>
</body>
</html>
External Stylesheets
External stylesheets are defined in separate CSS files and linked to HTML documents using the <link>
tag. This method is ideal for applying styles to multiple HTML documents, ensuring consistency across a website.
Syntax
<head>
<link rel="stylesheet" href="styles.css">
</head>
Example
HTML File
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>External Stylesheet</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
CSS File (styles.css)
body {
font-family: Arial, sans-serif;
}
h1 {
color: orange;
}
p {
font-size: 16px;
color: navy;
}
Conclusion
HTML styles are essential for controlling the appearance of your web pages. By using inline styles, internal styles, and external stylesheets, you can apply a wide range of formatting and design options to HTML elements. Understanding how to use styles effectively is crucial for creating visually appealing and user-friendly web pages.