facebook google plus twitter
Webucator's Free CSS Tutorial

Lesson: CSS and Links

Welcome to our free CSS tutorial. This tutorial is based on Webucator's Introduction to CSS Training course.

In this lesson you will learn to style links with CSS before, while, and after the user interacts with them.

Lesson Goals

  • Work with pseudo-classes.
  • Work with the a:hover selector.
  • Work with the a:visited selector.
  • Work with the a:active selector.
  • Work with the :target selector.

Pseudo-classes

The styles we have seen so far are attached to element names (e.g., div), class or id attributes (e.g., .big, #wrapper), or position in the page structure (e.g., ul ul). Pseudo-classes are used to classify elements by other means. The syntax of pseudo-classes is element:class.

Currently, the best supported pseudo-classes all apply to link states. A link can have the following pseudo-classes:

  • a:hover - indicates the mouse pointer is over the link
  • a:visited - indicates the link has been visited
  • a:active - indicates the link is active (e.g., the user has clicked down on it)

Code Sample:

Links/Demos/Links.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>CSS Links</title>
<style>
	a {
		color: #000066;
		text-decoration: none;
		cursor: pointer;
	}
	
	a:visited {
		color: #336699;
	}
	
	a:hover {
		color: #ff6600;
		text-decoration: underline;
	}
	
	a:active {
		color: #ffcc99;
		cursor: wait;
	}
</style>
</head>
<body>
<h1>CSS Links</h1>
<a href="http://www.washingtonpost.com">WashingtonPost.com</a><br>
<a href="http://www.webucator.com">Webucator</a><br>
<a href="http://www.google.com">Google</a><br>

<h3 style="color: red; margin-bottom: 2px;">Important Note</h3>

Order matters.  If <span style="font-family: monospace;">a: active</span> 
precedes <span style="font-family: monospace;">a: hover</span>,
the effects in <span style="font-family: monospace;">a: hover</span> will 
take precedence. So, in this example, you would not see the color 
change when the user clicks down on a link.

</body>
</html>

The code above will change how links look as the user interacts with them. To see the effects, open the page in a browser.

Note that a link can be in more than one state. For example, a link can be both visited and active. As a result, the order of the style rules matters.

If a:active precedes a:visited, then the rule for a:visited will take precedence. This means that, where there are conflicts, those properties defined for a:active will not be seen for visited links.

CSS Button Links

Using these pseudo-classes, it is possible to create links that look like buttons, something you needed images to do before CSS. The following example illustrates this:

Code Sample:

Links/Demos/LinkButtons.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>CSS Link Buttons</title>
<style>
div {
	width: 300px;
}

a {
	display: block;
	background-color: #eaf1dd;
	color: #060;
	text-decoration: none;
	font-family: Verdana, Geneva, sans-serif;
	font-size: 1.5em;
	padding: 6px 4px;
	margin: 4px;
	border-right: 2px solid #999999;
	border-bottom: 2px solid #999999;
	border-top-width: 0px;
	border-left-width: 0px;
}

a:hover
{
	color: #030;
	border: 1px solid #9999ff;
}

a:active
{
	color: #aca;
	border-left: 2px solid #030;
	border-top: 2px solid #030;
	border-right-width: 0px;
	border-bottom-width: 0px;
}
</style>
</head>
<body>
<h1>Button Links</h1>
<div>
	<a href="http://www.washingtonpost.com">WashingtonPost.com</a>
	<a href="http://www.webucator.com">Webucator</a>
	<a href="http://www.google.com">Google</a>
</div>
</body>
</html>

The screenshots below show how these CSS buttons look in different states: the default state, the hover state, and the active state. Note that some of the properties (e.g., border, margin, and padding) used in this have not yet been covered.

Default State Hover State Active State

The :target Selector

We use targets in URLs - that is, the attribute following the hash (#) in the URL - to open a given page not at the top of the page. A URL such as http://www.example.com/somepage.html#section1 would open the page somepage.html so that the element with id section1 is at the top of the browser (assuming there were enough content below the element to force a scroll). This is a useful way to link to specific content on a longer page.

CSS3 introduced the :target selector, a pseudo-class we can use to style the currently active target. A CSS rule such as

:target {
	background-color: #f00;
}

would style the linked-to element (a div, perhaps) with a red background color. The element would not be red if the element were not the current target. Here's a quick example:

Code Sample:

Links/Demos/Target.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>CSS Target</title>
<style>
	:target {
		background-color: #500000;
		border: 2px solid #000;
		color: #fff;
	}
	p {
		font-size: 20px;
		line-height: 24px;
		margin-bottom: 35px;
	}
</style>
</head>
<body>
<h1>CSS Target</h1>
<a href="#section1">Section 1</a><br>
<a href="#section2">Section 2</a><br>
<a href="#section3">Section 3</a><br>

<p id="section1">This is section 1. This is section 1. This is section 1. This is section 1. This is section 1. This is section 1. This is section 1. This is section 1. This is section 1. This is section 1. This is section 1. This is section 1.</p>
<hr>
<p id="section2">This is section 2. This is section 2. This is section 2. This is section 2. This is section 2. This is section 2. This is section 2. This is section 2. This is section 2. This is section 2. This is section 2. This is section 2.</p>
<hr>
<p id="section3">This is section 3. This is section 3. This is section 3. This is section 3. This is section 3. This is section 3. This is section 3. This is section 3. This is section 3. This is section 3. This is section 3. This is section 3.</p>
</body>
</html>

When first opened, the page displays two paragraphs with large text:

target

If the user clicks any of the links - all of which link to a target (either #section1, #section2, or #section3) - then the specified target receives the style from the :target selector, with a dark red background, white text color, and black border:

target - active

Modifying Links

Duration: 10 to 15 minutes.

In this exercise, you will modify the look and feel of the links in Stories.html.

  1. Open Links/Exercises/Stories.html.
  2. Modify the link styles on the page. You are also welcome to add additional links to the page. The object of this exercise is to get used to working with link properties and pseudo-classes.
  3. When you are done, open Stories.html in your browser to see the results. You are welcome to go back to the code and continue to work.

Solution:

Links/Solutions/Stories.html
<!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Stories</title>
    <style>
      h1 {
        font-family: Arial, Helvetica, sans-serif;
        font-size: x-large;
      }
      
      h2 {
        font-family: Arial, Helvetica, sans-serif;
        font-size: large;
        font-style: italic;
        font-weight: normal;
        letter-spacing: .25em;
        word-spacing: .4em;
        margin-bottom: 0px;
        text-align: center;
      }
    
      :target {
        font-weight: bold;
      }
    
      p {
        font-family: "Comic Sans MS", Times, serif;
        font-size: small;
        line-height: 1.2;
        text-indent: 2em;
      }
    
      #links {
        width: 300px;
      }
    
      a {
        display: block;
        background-color: #eaf1dd;
        color: #060;
        text-decoration: none;
        font-family: Verdana, Geneva, sans-serif;
        padding: 6px 4px;
        margin: 4px;
        border-right: 2px solid #999999;
        border-bottom: 2px solid #999999;
        border-top-width: 0px;
        border-left-width: 0px;
      }
    
      a:hover {
        color: #030;
        border: 1px solid #9999ff;
      }
    
      a:active {
        color: #aca;
        border-left: 2px solid #030;
        border-top: 2px solid #030;
        border-right-width: 0px;
        border-bottom-width: 0px;
      }
    
      .topLink {
        font-family: "Comic Sans MS";
        font-size: medium;
        font-variant: small-caps;
        font-style: normal;
        font-weight: normal;
      }
    
      .BackToTop {
        text-decoration: none;
        text-transform: capitalize;
        border-style: groove;
        border-color: #0000ff;
        border-bottom-width: 5px;
        border-left-width: 5px;
        border-top-width: 2px;
        border-right-width: 2px;
        padding: 4px;
        width: 280px;
      }
    
      div {
        padding-top: 2px;
        padding-left: 10px;
        padding-right: 10px;
        padding-bottom: 2px;
        margin-bottom: 15px;
      }
    </style>
    </head>
    <body>
    <h1 id="top">Stories</h1>
    <div id="links">
    <a href="#pooh" class="topLink">Pooh Goes Visiting</a><br>
    <a href="#alice" class="topLink">A Mad Tea-Party</a><br>
    <a href="#naughtyboy" class="topLink">The Naughty Boy</a><br>
    </div>
    <hr>
    
    <h2 id="pooh">POOH GOES VISITING - A.A. Milne</h2>
    <div style="background-image: url(Images/poohsmall.gif); 
          background-repeat: no-repeat; background-color:#ff9900; 
          color:#000066;">
    <p>Pooh always liked a little something at eleven o'clock in the morning, and he was very glad to see Rabbit getting out the plates and mugs; and when Rabbit said, 'Honey or condensed milk with your bread?' he was so exited that he said, 'Both' and then, so as not to seem greedy, he added, 'But don't bother about the bread, please.'</p>
    <p>And for a long time after that he said nothing...until at last, humming to himself in a rather sticky voice, he got up, shook Rabbit lovingly by the paw, and said that he must be going on. 'Must you?' said Rabbit politely. 'Well,' said Pooh, 'I could stay a little longer if it-if you-' and he tried very hard to look in the direction of the larder. 'As a matter of fact,' said Rabbit, 'I was going out myself directly.' 'Oh well, then, I'll be going on. Good bye.' 'Well good bye, if you're sure you won't have any more.' 'Is there any more?' asked Pooh quickly. Rabbit took the covers of the dishes, and said 'No, there wasn't.' 'I thought not,' said Pooh, nodding to himself. 'Well Good-bye, I must be going on.'</p>
    <p>So he started to climb out of the hole. He pulled with his front paws, and pushed with his back paws, and in a little while his nose was in the open again ... and then his ears ... and then his front paws ... and then his shoulders ... and then-'Oh, help!' said Pooh, 'I'd better go back,' 'Oh bother!' said Pooh, 'I shall have to go on.' 'I can't do either!' said Pooh, 'Oh help and bother!' ...</p>
    <p> ...Christopher Robin nodded. 'Then there's only one thing to be done,' he said. 'We shall have to wait for you to get thin again.' 'How long does getting thin take?' asked Pooh anxiously. 'About a week I should think.' 'But I can't stay here for a week!' 'You can stay here all right, silly old Bear. It's getting you out which is so difficult.' 'We'll read to you,' said Rabbit cheerfully. 'And I hope it won't snow,' he added. 'And I say, old fellow, you're taking up a good deal of room in my house - do you mind if I use your back legs as a towel-horse? Because, I mean, there they are - doing nothing - and it would be very convenient just to hang the towels on them. 'A Week!' said Pooh gloomily. 'What about meals?' 'I'm afraid no meals,' said Christopher Robin, 'because of getting thin quicker. But we will read to you.' Bear began to sigh, and then found he couldn't because he was so tightly stuck; and a tear rolled down his eye, as he said: 'Then would you read a Sustaining Book, such as would help and comfort a Wedged Bear in Great Tightness?' So for a week Christopher Robin read that sort of book at the North end of Pooh, and Rabbit hung his washing on the South end... and in between Bear felt himself getting slenderer and slenderer. And at the end of the week Christopher Robin said,</p>
    <p>'Now!'</p>
    <p>So he took hold of Pooh's front paws and Rabbit took hold of Christopher Robin, and all Rabbit's friends and relations took hold of Rabbit, and they all pulled together ... And for a long time Pooh only said 'Ow!' ... And 'Oh!' ... And then, all of a sudden he said 'Pop!' just if a cork were coming out of a bottle. And Christopher Robin and Rabbit and all relations went head-over-heels backwards ...and on top of them came Winnie-the-Pooh free! So with a nod of thanks to his friends, he went on with his walk through the forest, humming proudly to himself. But Christopher Robin looked after him lovingly, and said to himself 'Silly Old Bear!'</p>
    </div> 
    <a href="#top" class="BackToTop">Back to top</a>
    <hr>
    
    <h2 id="alice">A MAD TEA-PARTY - Lewis Carroll</h2>
    <div style="background-image: url(Images/TeaParty.gif); 
          background-position: right; background-repeat: no-repeat;">
    <p>There was a table set out under a tree in front of the house, and the March Hare and the Hatter were having tea at it: a Dormouse was sitting between them, fast asleep, and the other two were using it as a cushion, resting their elbows on it, and the talking over its head. 'Very uncomfortable for the Dormouse,' thought Alice; 'only, as it's asleep, I suppose it doesn't mind.'</p>
    <p>The table was a large one, but the three were all crowded together at one corner of it: 'No room! No room!' they cried out when they saw Alice coming. 'There's plenty of room!' said Alice indignantly, and she sat down in a large arm-chair at one end of the table.</p>
    <p>'Have some wine,' the March Hare said in an encouraging tone.</p>
    <p>Alice looked all round the table, but there was nothing on it but tea. 'I don't see any wine,' she remarked.</p>
    <p>'There isn't any,' said the March Hare.</p>
    <p>'Then it wasn't very civil of you to offer it,' said Alice angrily.</p>
    <p>'It wasn't very civil of you to sit down without being invited,' said the March Hare.</p>
    <p>'I didn't know it was your table,' said Alice; 'it's laid for a great many more than three.'</p>
    <p>'Your hair wants cutting,' said the Hatter. He had been looking at Alice for some time with great curiosity, and this was his first speech.</p>
    <p>'You should learn not to make personal remarks,' Alice said with some severity; 'it's very rude.'</p>
    <p>The Hatter opened his eyes very wide on hearing this; but all he said was, 'Why is a raven like a writing-desk?'</p>
    <p>'Come, we shall have some fun now!' thought Alice. 'I'm glad they've begun asking riddles.--I believe I can guess that,' she added aloud.</p>
    <p>'Do you mean that you think you can find out the answer to it?' said the March Hare.</p>
    <p>'Exactly so,' said Alice. </p>
    <p>'Then you should say what you mean,' the March Hare went on.</p>
    <p>'I do,' Alice hastily replied; 'at least--at least I mean what I say--that's the same thing, you know.'</p>
    </div>
    <a href="#top" class="BackToTop">Back to top</a>
    <hr>
    
    <h2 id="naughtyboy">THE NAUGHTY BOY - Hans Christian Andersen</h2>
    
    <div style="background-image: url(Images/Cupid.gif); color: #ff3333;">
    <p>Along time ago, there lived an old poet, a thoroughly kind old poet. As he was sitting one evening in his room, a dreadful storm arose without, and the rain streamed down from heaven; but the old poet sat warm and comfortable in his chimney-comer, where the fire blazed and the roasting apple hissed.</p>
    <p>"Those who have not a roof over their heads will be wetted to the skin," said the good old poet.</p>
    <p>"Oh let me in! Let me in! I am cold, and I'm so wet!" exclaimed suddenly a child that stood crying at the door and knocking for admittance, while the rain poured down, and the wind made all the windows rattle.</p>
    <p>"Poor thing!" said the old poet, as he went to open the door. There stood a little boy, quite naked, and the water ran down from his long golden hair; he trembled with cold, and had he not come into a warm room he would most certainly have perished in the frightful tempest.</p>
    <p>"Poor child!" said the old poet, as he took the boy by the hand. "Come in, come in, and I will soon restore thee! Thou shalt have wine and roasted apples, for thou art verily a charming child!" And the boy was so really. His eyes were like two bright stars; and although the water trickled down his hair, it waved in beautiful curls. He looked exactly like a little angel, but he was so pale, and his whole body trembled with cold. He had a nice little bow in his hand, but it was quite spoiled by the rain, and the tints of his many-colored arrows ran one into the other.</p>
    <p>The old poet seated himself beside his hearth, and took the little fellow on his lap; he squeezed the water out of his dripping hair, warmed his hands between his own, and boiled for him some sweet wine. Then the boy recovered, his cheeks again grew rosy, he jumped down from the lap where he was sitting, and danced round the kind old poet.</p>
    <p>"You are a merry fellow," said the old man. "What's your name?"</p>
    <p>"My name is Cupid," answered the boy. "Don't you know me? There lies my bow; it shoots well, I can assure you! Look, the weather is now clearing up, and the moon is shining clear again through the window."</p>
    <p>"Why, your bow is quite spoiled," said the old poet.</p>
    <p>"That were sad indeed," said the boy, and he took the bow in his hand -and examined it on every side. "Oh, it is dry again, and is not hurt at all; the string is quite tight. I will try it directly." And he bent his bow, took aim, and shot an arrow at the old poet, right into his heart. "You see now that my bow was not spoiled," said he laughing; and away he ran.</p>
    <p>The naughty boy, to shoot the old poet in that way; he who had taken him into his warm room, who had treated him so kindly, and who had given him warm wine and the very best apples!</p>
    <p>The poor poet lay on the earth and wept, for the arrow had really flown into his heart.</p>
    <p>"Fie!" said he. "How naughty a boy Cupid is! I will tell all children about him, that they may take care and not play with him, for he will only cause them sorrow and many a heartache."</p>
    <p>And all good children to whom he related this story, took great heed of this naughty Cupid; but he made fools of them still, for he is astonishingly cunning. When the university students come from the lectures, he runs beside them in a black coat, and with a book under his arm. It is quite impossible for them to know him, and they walk along with him arm in arm, as if he, too, were a student like themselves; and then, unperceived, he thrusts an arrow to their bosom. When the young maidens come from being examined by the clergyman, or go to church to be confirmed, there he is again close behind them. Yes, he is forever following people. At the play, he sits in the great chandelier and burns in bright flames, so that people think it is really a flame, but they soon discover it is something else. He roves about in the garden of the palace and upon the ramparts: yes, once he even shot your father and mother right in the heart. Ask them only and you will hear what they'll tell you. Oh, he is a naughty boy, that Cupid; you must never have anything to do with him. He is forever running after everybody. Only think, he shot an arrow once at your old grandmother! But that is a long time ago, and it is all past now; however, a thing of that sort she never forgets. Fie, naughty Cupid! But now you know him, and you know, too, how ill-behaved he is!</p>
    </div>
    <a href="#top" class="BackToTop">Back to top</a>
    </body>
    </html>