Module 3: Advanced CSS Techniques
Day 11: Advanced Selectors, Pseudo-classes, and Pseudo-elements
Advanced Selectors
Advanced selectors allow for more specific targeting of elements within your HTML. Here are some examples:
/* Descendant selector */
div p {
color: blue;
}
/* Child selector */
div > p {
color: green;
}
/* Adjacent sibling selector */
h1 + p {
color: red;
}
/* General sibling selector */
h1 ~ p {
color: purple;
}
/* Attribute selector */
input[type="text"] {
background-color: yellow;
}
Example:
<div>
<p>This paragraph is a descendant of a div.</p>
<h1>Heading</h1>
<p>This paragraph is adjacent to a h1.</p>
<p>This paragraph is a sibling of a h1.</p>
<input type="text" value="Text input">
</div>
Pseudo-classes
Pseudo-classes are used to define the special state of an element. Here are some examples:
/* Hover state */
a:hover {
color: red;
}
/* Visited link */
a:visited {
color: green;
}
/* First child */
p:first-child {
font-weight: bold;
}
/* Last child */
p:last-child {
font-style: italic;
}
/* nth child */
p:nth-child(2) {
text-decoration: underline;
}
Example:
<a href="#">Hover over me</a>
<p>First paragraph</p>
<p>Second paragraph</p>
<p>Last paragraph</p>
Pseudo-elements
Pseudo-elements are used to style specified parts of an element. Here are some examples:
/* First letter */
p::first-letter {
font-size: 2em;
color: red;
}
/* First line */
p::first-line {
font-weight: bold;
}
/* Before */
p::before {
content: "Prefix: ";
color: blue;
}
/* After */
p::after {
content: " Suffix.";
color: green;
}
Example:
<p>This is a paragraph to demonstrate pseudo-elements.</p>