Geek Slack

Introduction to CSS
About Lesson



CSS Pseudo-classes


CSS Pseudo-classes

CSS pseudo-classes are used to define the special state of an element. They can be used to style elements based on their state or position in the document tree.

1. Link Pseudo-classes

Link pseudo-classes are used to style links in different states. The common link pseudo-classes are :link, :visited, :hover, and :active.

Example:

<a href="#">Link Example</a>

<style>
a:link {
    color: #2196f3;
}
a:visited {
    color: #9c27b0;
}
a:hover {
    color: #ff5722;
}
a:active {
    color: #f44336;
}
</style>

Link Example

2. Structural Pseudo-classes

Structural pseudo-classes allow you to select elements based on their position in the document tree. Common examples include :first-child and :nth-child().

Example 1: :first-child

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

<style>
li:first-child {
    background-color: #c8e6c9;
}
</style>
  • Item 1
  • Item 2
  • Item 3

Example 2: :nth-child(even)

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
</ul>

<style>
li:nth-child(even) {
    background-color: #e1bee7;
}
</style>
  • Item 1
  • Item 2
  • Item 3
  • Item 4

3. Form Pseudo-classes

Form pseudo-classes are used to style form elements based on their state. Examples include :focus and :checked.

Example 1: :focus

<input type="text" placeholder="Focus on me">

<style>
input:focus {
    border: 2px solid #4caf50;
}
</style>

Example 2: :checked

<input type="checkbox" id="checkbox">
<label for="checkbox">Check me</label>

<style>
input:checked + label {
    font-weight: bold;
    color: #ff5722;
}
</style>


Conclusion

CSS pseudo-classes are powerful tools for selecting elements based on their state or position in the document tree. By using pseudo-classes, you can create dynamic and interactive styles for your web pages.

Join the conversation