Pseudo-classes in CSS are used to select and style elements based on their state or position within the document tree. They allow us to target specific elements that cannot be selected using regular selectors alone.
There are several types of pseudo-classes in CSS, including:
- Structural Pseudo-classes: These pseudo-classes select elements based on their position within the document tree. Examples include
:first-child
,:last-child
,:nth-child
, etc. For example,:first-child
selects the first child element of its parent. - Link Pseudo-classes: These pseudo-classes select elements based on their link state. Examples include
:link
,:visited
,:hover
,:active
, etc. For example,:hover
selects an element when the user hovers over it. - Form Pseudo-classes: These pseudo-classes select form elements based on their state. Examples include
:checked
,:disabled
,:focus
, etc. For example,:checked
selects a radio button or checkbox when it is checked. - UI Element States Pseudo-classes: These pseudo-classes select elements based on their user interface state. Examples include
:enabled
,:disabled
,:checked
, etc. For example,:enabled
selects an enabled form element.
To demonstrate the usage of pseudo-classes in JavaScript and HTML, let’s consider an example where we want to style the first paragraph element inside a div with a class of “container” differently:
// JavaScript code const containerDiv = document.querySelector('.container'); const firstParagraph = containerDiv.querySelector('p:first-child'); firstParagraph.classList.add('highlight');
<!-- HTML code -->
<div class="container">
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
</div>
<style>
.highlight {
color: red;
font-weight: bold;
}
</style>
In the above example, we use JavaScript to select the first paragraph element inside the div with the class “container”. Then, we add a CSS class called “highlight” to the selected element. Finally, we define the styles for the “highlight” class in the CSS section, making the text red and bold.
This is just one example of how pseudo-classes can be used in combination with JavaScript and HTML to achieve specific styling effects. Pseudo-classes provide a powerful way to target and style elements based on their state or position, enhancing the flexibility and interactivity of web pages.