CSS Hover



CSS Tutorial  >  Hover

The :hover pseudo-class is used to specify the effects of hovering, or mousing over, an object. To define a hover effect, add ":hover" after the element you want to modify in the CSS. For example, to define the hover characteristics for a link, use,

a:hover { [some CSS property] }

To define the hover characteristics for a class, use,

.[class-name] { [some CSS properties] }

The most common use of :hover is with a link. Often, web designers will design the web page so that when the user mouses over a link, the link changes shape in some form. It could be a color change, a font size change, the appearance of an underline, or a background change. There are two examples of the :hover effect in this tutorial:

  • On the navigation on the left, hovering over a link changes the background color.
  • In the body text, hovering over a link adds an underline.

The two examples below show how each is done.

Example 1: Use :hover to change the background color of the link

CSS Declaration

a:hover {background-color: #ccc;}

which results in the following:

Example 2: Use :hover to add an underline to a link

CSS Declaration

a:hover {text-decoration: underline;}

which results in the following:

In addition to the link, the entire background of an element can be changed using :hover, as the next example shows:

Example 3: Use :hover to add an underline to a link

CSS Declaration

.background-change:hover {background-color: yellow;}

The following HTML code,

<div class="background-change">Hover this element to get yellow background</div>

results in the following:

:Hover can also be used on an image. In the example below, :hover is used to add a border to an image.

Example 4: Use :hover to add a border to an image

CSS Declaration

.pic:hover {border-style:solid; border-width:10px;}

The following HTML code,

<img class="pic" src="1keydata.gif" />

results in the following:

:Hover can also be used to style a drop-down menu in navigation in pure CSS (in other words, without using JavaScript code). The idea is that when the user hovers over the menu, the sub-menu items would appear.

Next: CSS :first-child




Copyright © 2017   1keydata.com   All Rights Reserved   Privacy Policy   About   Contact