CSS Selectors are an essential part of Cascading Style Sheets (CSS) that allow developers to target specific HTML elements and apply styles to them. Selectors are used to define the style rules that determine how an HTML element should be displayed on a web page. In this tutorial, we will explore the different types of CSS selectors and how they can be used to style HTML elements.
There are several types of CSS selectors that can be used to target HTML elements. These include:
Element selectors are used to target HTML elements based on their tag name. For example, the following CSS rule targets all <p>
elements:
<style>
p {
color: red;
}
</style>
ID selectors are used to target HTML elements based on their unique ID attribute. For example, the following CSS rule targets the element with the ID "header":
<style>
#header {
background-color: blue;
}
</style>
Class selectors are used to target HTML elements based on their class attribute. For example, the following CSS rule targets all elements with the class "highlight":
<style>
.highlight {
font-weight: bold;
}
</style>
Attribute selectors are used to target HTML elements based on their attribute values. For example, the following CSS rule targets all elements with the "href" attribute:
<style>
[href] {
color: green;
}
</style>
Universal selectors are used to target all HTML elements on a web page. For example, the following CSS rule targets all elements:
<style>
* {
margin: 0;
padding: 0;
}
</style>
Descendant selectors are used to target HTML elements that are descendants of other HTML elements. For example, the following CSS rule targets all <li>
elements that are descendants of <ul>
elements:
<style>
ul li {
list-style-type: none;
}
</style>
Child selectors are used to target HTML elements that are direct children of other HTML elements. For example, the following CSS rule targets all <li>
elements that are direct children of <ul>
elements:
<style>
ul > li {
list-style-type: none;
}
</style>
Adjacent sibling selectors are used to target HTML elements that are immediately adjacent to other HTML elements. For example, the following CSS rule targets the <p>
element that immediately follows a <h1>
element:
<style>
h1 + p {
font-size: 18px;
}
</style>
General sibling selectors are used to target HTML elements that are siblings of other HTML elements. For example, the following CSS rule targets all <p>
elements that are siblings of <h1>
elements:
<style>
h1 ~ p {
font-size: 16px;
}
</style>
CSS selectors are a powerful tool for web developers to style HTML elements on a web page. By understanding the different types of selectors and how they can be used, developers can create visually appealing and user-friendly web pages.