2. pseudo-class syntax
Given below is the basic syntax of using pseudo-classes. Take note that in this module, you are not only limited to links for selectors.
selector:pseudo-class {
property: value;
}
Pseudo-classes can also be combined with other CSS classes. Given below is an example of a div tag with class content. It will change color upon hover.
div.content:hover {
color: #ff0000;
}
Another combination that can be done with pseudo-classes is with CSS element selectors. Take, for example, a div element that a user will hover upon. But instead of styling the div element upon hover, another HTML element will be styled, which in this
example, will be a p element. The code listed below is an example of a p element becoming visible when a div element is hovered upon. You are encouraged to copy and save the code into an HTML file in your text editor to see the result. Run the code using the Try It Yourself Editor
- <!DOCTYPE html>
- <html>
- <head>
- <style>
- p {
- display: none; /* this hides the p element */
- background-color: green;
- padding: 20px;
- }
- div:hover p { /* this will display the p element when user hovers over the div */
- display: block;
- }
- </style>
- </head>
- <body>
- <div>Hover over me to show the p element
- <p>This is a p element</p>
- </div>
- </body>
- </html>
There are many pseudo-classes available in CSS. You can check them out here: CSS Pseudo Classes (https://www.w3schools.com/css/css_pseudo_classes.asp).
Here are some pseudo-classes from the link given above. You will encounter them more often than other pseudo-classes during our activities for this class.
| Pseudo-class
|
Description
|
|---|---|
| selector:active
|
Selects the active selector
|
| selector:checked
|
Selects all checked elements. Example is in checkboxes
|
| selector:disabled
|
Selects all disabled elements. Example is in textboxes that cannot be edited or buttons that cannot be clicked unless an action is done
|
| selector:focus
|
Selects the element that has focus (i.e., a textbox where the cursor is currently at)
|
| selector:valid
|
Selects all elements with a valid value (i.e., a textbox for passwords with a valid input)
|