CSS selectors are used to select the HTML elements you want to style. They are a fundamental part of CSS, allowing you to apply styles to specific elements in your HTML document. Here's an overview of the most common types of CSS selectors:
- Selects elements based on the HTML tag name.
p {
color: blue;
}
- Selects an element based on its unique `id` attribute.
- Prefixed with a `#`.
- Example: `#header` selects the element with `id="header"`.
#header {
background-color: gray;
}
- Selects elements based on their `class` attribute.
- Prefixed with a `.`
- Example: `.highlight` selects all elements with `class="highlight"`.
.highlight {
font-weight: bold;
}
- Selects all elements on the page.
- Represented by `*`.
* {
margin: 0;
padding: 0;
}
- Selects multiple elements and applies the same style to all of them.
- Elements are separated by a comma.
h1, h2, h3 {
color: green;
}
These selectors allow for precise and efficient styling of HTML elements, making your web pages more organized and visually appealing.
<!DOCTYPE html>
<head>
<title>CSS Selectors Example</title>
<style>
/* Element Selector */
p {
color: blue;
}
/* Id Selector */
#header {
background-color: gray;
color: white;
padding: 10px;
}
/* Class Selector */
.highlight {
font-weight: bold;
background-color: yellow;
}
/* Universal Selector */
* {
font-family: Arial, sans-serif;
}
/* Group Selector */
h1, h2, h3 {
color: green;
}
</style>
</head>
<body>
<div id="header">
<h1>Header Section</h1>
</div>
<h2>Subheader</h2>
<h3>Another Subheader</h3>
<p>This is a paragraph that will be styled using the element
selector.</p>
<p class="highlight">This is a highlighted paragraph styled using the class
selector.</p>
</body>
</html>
This is a paragraph that will be styled using the element selector.
This is a highlighted paragraph styled using the class selector.