What are the different ways to apply CSS styles to HTML elements?
CSS styles can be applied to HTML elements in several ways:
Inline Styles
Internal Stylesheet
External Stylesheet
Selectors and Classes
IDs
Inline Styles:
Inline styles are applied directly to individual HTML elements using the
`style`
attribute. This method is suitable for making one-off style changes to a specific element. Inline styles
have high specificity, which means they override other styles. Example:
<p style="color: blue; font-size: 16px;">This is a blue paragraph.</p> Output:
This is a blue paragraph.
Internal Stylesheet:
An internal stylesheet is defined within the HTML document using the
`<style>
` element. It typically appears within the `<head>` section of the HTML document. Internal styles
affect elements on that specific page. Example:
<html>
<head>
<style>
p {
color: red;
font-size: 18px;
}
</style>
</head>
<body>
<p>This is an example paragraph. </p>
</body>
</html> Output:
This is an example paragraph.
External Stylesheet:
An external stylesheet is a separate CSS file that is linked to multiple
HTML documents. This method is the most common for maintaining consistent styles across an entire website.
The CSS file is linked in the HTML document's `<head>` section using the `<link>` element. Example:
first.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<p>This is an example paragraph. </p>
</body>
</html>
styles.css
p
{
color:red;
} Output:
This is an example paragraph.
In this case, `styles.css` is the external CSS file containing the style rules.
Selectors and Classes:
CSS selectors and classes allow to target specific HTML elements for
styling.
Define CSS rules that apply to elements with specific attributes or classes. To apply styles using an Class,
we use the `.` symbol followed by the Class name in our CSS rules. Example:
<html>
<head>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<p class="highlight">This paragraph has a yellow background.</p>
</body>
</html> Output:
This paragraph has a yellow background.
In this example, the `.highlight` class is used to style the paragraph.
IDs:
CSS IDs are used to target a single unique HTML element. While we can use them for
styling, it's generally recommended to reserve IDs for JavaScript interactions or linking within the same
page. To apply styles using an ID, we use the `#` symbol followed by the ID name in our CSS rules. Example:
<html>
<head>
<style>
#unique-paragraph {
color:red
font-weight: bold;
}
</style>
</head>
<body>
<p id="unique-paragraph">This paragraph has bold text.</p>
</body>
</html> Output: