Hey there, and welcome to Argee’s first tutorial! This one is pretty simple, we will just be walking through the nuances of the :hover selector in CSS.
This selector,like most styles, can be applied to absolutely any HTML element in your web page to create a rollover effect. A lot of people still use javascript to do this, which works but is deprecated. In other words, this is the ninja way to do things.
1. Applying hover to a link element
Say that you have the following element in your web page, just a basic link with the id ‘my-link’.
<a id="my-link">Hi, I am a link!</a>
The id tag lets us apply a style specifically to this element - a web page may only have one instance of a given id, which means you can’t give the id of ‘my-link’ to any more elements on your page. Let the following be the link you wish to apply styling to:
<a id="my-link">Hi, I am a link!</a>
Now, to apply the actual hover effect, you would put the following code in your CSS - which should preferably be an external stylesheet.
/* Style when no hover */
#my-link {
color: #ccc;
text-decoration: none;
}
/* Style when mouse-overed */
#my-link:hover {
color: #000;
text-decoration: underline;
}
This will give you a basic text link that changes color and is underlined upon mouse over. Not good enough for you? Well, read on over to the next section…
2. Applying hover to a div element
What’s great about cascading style is it’s versatility - it can be applied to any kind of element to change it’s appearance in various ways. Let the following be the div element that you wish to apply styling to:
<div id="my-div">Hi, I am a div!</div>
I will give you a basic example, keep in mind that which styles you apply is totally up to you.
/* Style when no hover */
#my-div {
color: #ccc;
background-color: #fff;
text-decoration: none;
font-family: Georigia, serif;
padding: 5px;
}
/* Style when mouse-overed */
#my-div:hover {
color: #000;
background-color:#ddd;
text-decoration: underline;
border: 1px solid #000;
}
This should give you a div element that changes in appearance when hovered over. Of course, these are only example styles - you may choose to apply a different, better styling to your elements.
Note that while we only experimented with <a> and <div> tags here, the hover selector can be used for styling any HTML tags.
Well, that was all. Not too tough, was it? Hope you enjoy your new-found skills!