Categories
CSS Web development

CSS :hover and :active selectors

The CSS selectors select the HTML elements which you want to style.

CSS :hover and :active selectors
*to see the demo and the code of the animation above click here.

The CSS :hover selector is used to select the element when you mouse over it.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
	
.square {
	width:100px;
	height: 100px;
	background-color: #2a9d8f;
	}
.square:hover {
  background-color: #e9c46a;
}
</style>
</head>
<body>

<p>Hover over the square:</p>
<div class="square"></div>

</body>
</html>

Output:

Hover over the square:

To make the change of the selected element smoother you can add to the :hover selector the transition property.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
	
.square {
	width:100px;
	height: 100px;
	background-color: #2a9d8f;
	transition: .5s;
	}
.square:hover {
  background-color: #e9c46a;
}
</style>
</head>
<body>

<p>Hover over the square:</p>
<div class="square"></div>

</body>
</html>

Output:

Hover over the square:

The CSS :active selector is used to change the appearance of a link /HTML element while it is being activated (being clicked).

Example:

<!DOCTYPE html>
<html>
<head>
<style>
	
.square {
	width:100px;
	height: 100px;
	background-color: #2a9d8f;
	}
.square:active {
  background-color: #e9c46a;
}
</style>
</head>
<body>

<p>Hover over the square:</p>
<div class="square"></div>

</body>
</html>

Output:

Click on the square:

Using the CSS :hover and :active selectors you can style links with different styles:

<!DOCTYPE html>
<html>
<head>
<style>
	
p {color: #333; font-size: 20px;font-family: arial;}
	
a.link-1:hover, a.link-1:active {color: #2a9d8f;}
a.link-2:hover, a.link-2:active {font-size: 35px;}
a.link-3:hover, a.link-3:active {background-color: #2a9d8f;}
a.link-4:hover, a.link-4:active {font-family: 'Brush Script MT', cursive;}
a.link-5:visited, a.link-5:link {text-decoration: none;}
a.link-5:hover, a.link-5:active {text-decoration: underline;}
</style>
</head>
<body>

<p>Hover over the links to see effects.</p>

<p><a class="link-1" href="">This link changes color</a></p>
<p><a class="link-2" href="">This link changes font-size</a></p>
<p><a class="link-3" href="">This link changes background-color</a></p>
<p><a class="link-4" href="">This link changes font-family</a></p>
<p><a class="link-5" href="">This link changes text-decoration</a></p>

</body>
</html>

Output:

Hover over the links to see effects.

Enjoy coding!

Read also:

CSS :focus & :focus-within Selectors

CSS :checked Selector

CSS :not Selector