Introduction to CSS Selectors
CSS (Cascading Style Sheets) selectors are patterns used to select and style HTML elements on a web page. They allow developers to target specific elements or groups of elements and apply styles to them. CSS selectors come in various types, each serving a different purpose and providing flexibility in styling web pages.
1. Element Selectors
Element selectors target HTML elements based on their tag names. They apply styles to all occurrences of the specified element throughout the document. Element selectors are the simplest type of selectors and are denoted by the element's tag name.
Example:
/* Targeting all <p> elements */
p {
color: blue;
}
In this example, the color: blue; style rule applies to all <p>
elements, making their text color blue.
2. Class Selectors
Class selectors target HTML elements based on their class attribute values. They allow developers to apply styles to specific groups of elements with the same class name. Class selectors are denoted by a period (.) followed by the class name.
Example:
<!-- HTML -->
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<style>
/* Targeting elements with the class "box" */
.box {
background-color: lightgray;
border: 1px solid black;
}
</style>
In this example, all elements with the class "box" will have a light gray background and a black border.
ID selectors target HTML elements based on their id attribute values, which should be unique within the document. They allow developers to apply styles to individual elements. ID selectors are denoted by a hash (#) followed by the ID value.
Example:
<div id="header">Header</div>
<style>
/* Targeting the element with the ID "header" */
#header {
font-size: 24px;
font-weight: bold;
}
<s/tyle>
In this example, the element with the ID "header" will have a font size of 24 pixels and bold text.
4. Attribute Selectors
Attribute selectors target HTML elements based on the presence or value of their attributes. They allow developers to style elements with specific attribute conditions. Attribute selectors can be used to target elements with certain attributes, attribute values, or attribute values containing specific substrings.
Example:
<a href="https://example.com">Link</a>
<input type="text" required>
<style>
/* Targeting links with a "href" attribute */
a[href] {
color: blue;
}
/* Targeting input elements with the "required" attribute */
input[required] {
border-color: red;
}
</style>
In this example, all links (<a>
elements) with an href attribute will have blue text, and all input elements (<input>
elements) with the required attribute will have a red border.
Practice Excercise Practice now