Chapter 9: Advanced CSS Selectors
9.1 Introduction to CSS Selectors
CSS selectors define the elements to which a set of CSS rules apply. In this chapter, you will learn advanced selectors that allow you to target elements with precision.
9.2 Types of Advanced CSS Selectors
- Pseudo-classes: Apply styles based on the element's state (e.g.,
:hover
,:nth-child()
). - Pseudo-elements: Style specific parts of an element (e.g.,
::before
,::after
). - Attribute selectors: Target elements based on attributes and their values.
- Combinators: Define relationships between elements (e.g., child, sibling).
9.3 Example: Pseudo-classes
Pseudo-classes are used to define a special state of an element. For instance:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
a {
color: blue;
text-decoration: none;
}
a:hover {
color: red;
text-decoration: underline;
}
li:nth-child(odd) {
background-color: #f0f0f0;
}
</style>
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
<a href="#">Hover over me!</a>
</body>
</html>
9.4 Example: Pseudo-elements
Pseudo-elements allow you to style specific parts of an element:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
p::first-line {
font-weight: bold;
color: #007bff;
}
p::after {
content: " (Read more)";
color: gray;
}
</style>
</head>
<body>
<p>This is an example of pseudo-elements in CSS. Watch how it styles the first line and adds text after the paragraph.</p>
</body>
</html>
9.5 Example: Attribute Selectors
Attribute selectors target elements based on their attributes:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
input[type="text"] {
border: 2px solid #007bff;
}
input[placeholder] {
color: gray;
font-style: italic;
}
</style>
</head>
<body>
<form>
<input type="text" placeholder="Enter your name">
<input type="submit" value="Submit">
</form>
</body>
</html>
9.6 Example: Combinators
Combinators define relationships between elements. For example:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
ul > li {
font-weight: bold;
}
h2 + p {
color: gray;
}
</style>
</head>
<body>
<ul>
<li>Parent-child combinator example</li>
</ul>
<h2>Heading</h2>
<p>This paragraph comes immediately after a heading.</p>
</body>
</html>
9.7 Summary
In this chapter, you learned about advanced CSS selectors, including pseudo-classes, pseudo-elements, attribute selectors, and combinators. These tools allow for precise styling of elements. Next, we will explore CSS transitions and animations in Chapter 10.
0 Comments