What is Pseudo-class in CSS


CSS Pseudo Classes are representation of special states of different elements, these classes not only depict basic elements in document but also their external factors such status, position, history, etc. Using these pseudo classes developer can even style elements which cannot be directly selected via CSS selectors.

Syntax

Following is the syntax of using CSS Pseudo classes on an element −

Selector:pseudo-class {
   css-property: /*value*/;
}

Example

Let’s see an example to use CSS Pseudo Classes −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<title>CSS Pseudo Class</title>
<style>
form {
   width:70%;
   margin: 0 auto;
   text-align: center;
}
* {
   padding: 2px;
   margin:5px;
}
input:valid {
   color: #fefefe;
   background-color: #4CAF50;
}
input:invalid {
   color: #fefefe;
   background-color: #DC3545;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>CSS Pseudo Class</legend>
<label for="EmailSelect">Email :
<input type="email" id="EmailSelect" size="25" required>
</label><br>
<label for="PassSelect">Password :
<input type="password" id="PassSelect" minlength="8" required>
</label>
<div id="divDisplay">Min. Strength of Password: 8<br>Both Fields are Required</div>
</fieldset>
</form>
</body>
</html>

Output

This will produce the following output −

When the form fields have invalid data −

When the form fields have valid data −

Example

Let’s see another example of CSS Pseudo classes −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<title>CSS Pseudo Class</title>
<style>
form {
   width:70%;
   margin: 0 auto;
   text-align: center;
}
* {
   padding: 2px;
   margin:5px;
}
a {
   text-decoration: none;
   background:grey;
   color: white;
   border-radius: 3px;
   padding: 6px;
}
input[type="button"] {
   border-radius: 10px;
}
:target {
   border:4px solid black;
   margin: 0 auto;
   height: 200px;
   width: 200px;
   background-image: url('https://www.tutorialspoint.com/arangodb/images/arangodb-mini-logo.jpg');
}
#circle {
   border-radius: 50%;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>CSS Pseudo Class</legend>
<div>
<div id="circle"></div>
<div id="square"></div>
</div>
<div>
<a href="#square">Tile</a>
<a href="#circle">Avatar</a>
</div>
</fieldset>
</form>
</body>
</html>

Output

This will produce the following output −

Before clicking any button −

After clicking ‘Tile’ button −

After clicking ‘Avatar’ button −

Updated on: 07-Jan-2020

104 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements