HTML styles can be applied to HTML elements to change their appearance, such as font size, font color, background color, padding, margin, and more. Styles can be applied using inline styles, internal styles, or external styles.
Inline styles are applied directly to an HTML element using the style
attribute. Here’s an example:
<p style="color: red; font-size: 20px;">This text is red and 20 pixels in size.</p>
Internal styles are defined within the <head>
section of an HTML document using the <style>
tag. Here’s an example:
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: blue;
font-size: 16px;
}
</style>
</head>
<body>
<p>This text is blue and 16 pixels in size.</p>
</body>
</html>
In this example, the styles are applied to all <p>
tags within the document. Note that internal styles should be used sparingly, as they can make the HTML code less readable and harder to maintain.
External styles are defined in a separate CSS file, which is linked to the HTML document using the <link>
tag. Here’s an example:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>This text is styled using an external CSS file.</p>
</body>
</html>
In this example, the styles are defined in a file called styles.css
, which is located in the same directory as the HTML file. The styles defined in the CSS file can be applied to any HTML element in the document.
Using external styles is generally the best practice, as it separates the style information from the HTML content and makes it easier to maintain and update the styles across multiple pages.