Trang chủ‎ > ‎IT‎ > ‎WEB PROGRAMMING‎ > ‎02 - CSS‎ > ‎

Tutorial - Building website using HTML5 and CSS3 - CSS Introduction

Setting up CSS

Log in or subscribe for free to enjoy all this course has to offer!

Having spent the first part of the course working on HTML only, we're now going to find out about CSS that I deliberately sidelined. CSS is no more complicated than HTML. It supplements HTML to help you format your web page.

This first chapter on CSS deals with the theory behind it: what is it? What does it look like? Where do you write the CSS code? Although these theoretical aspects are not very complicated, you need to know about them as it's the very basis of CSS. And it's the only thing I'm going to ask you to remember by heart in CSS as you can find the rest in the memo in the appendix.

So let's get going, I can see that you are burning with impatience!

The story behind CSS

I warned you about this right at the start of this course: we're going to learn two languages. We've already found out quite a lot about HTML, even if there are still quite a few things to learn (we'll come back to it in a few chapters). However, it's now time to concern ourselves with CSS.

CSS (Cascading Style Sheets), is the other language that complements HTML. 
Do you remember what its purpose is? To manage the formatting of your website.

Brief reminder: what is CSS used for?

CSS? It's what allows you to choose the color of your text. 
It's also what allows you to select the font used on your website.
And it's also what allows you to set the text size, borders, background, etc.

And also what you use for the page layout of your website. You can use it to say: I want my menu to be on the left and be just so wide, I want my website header to be top-aligned and always visible, etc.

Remember this little comparison that we saw in the first chapter (next figure).

With and without CSSWith and without CSS

We used HTML to write the content of our website but it was rough around the edges. CSS supplements this code to format the whole content and give the appearance that you want.

CSS: a hesitant start

It should be pointed out that CSS didn't exist at the time the Web started. There was only HTML to start with, in fact.
HTML was created in 1991 and CSS in 1996. So you're probably wondering: how did they format text from 1991 to 1996? Well actually, in HTML alone! Indeed, there used to be HTML tags for formatting. <font color="#aab1c3">, for example, was used to define the text color.

However, HTML pages began to get quite complex. There were ever more tags with a nice mess between content and form, which made updating web pages increasingly complex. That's why the CSS language was created.

CSS was not immediately adopted by webmasters, however, far from it. A number of bad habits had to be discarded and this took time. Even now, you can still find websites with old, obsolete HTML formatting tags, such as <font>!

CSS: support for browsers

CSS has changed, just like HTML. I told you that there were four major versions of CSS:

  • CSS 1;

  • CSS 2.0;

  • CSS 2.1;

  • CSS 3.

In fact, the CSS 3 version is not yet fully finalized (it's not yet an official version). You can already use it, however, as it is now well advanced and already supported by many browsers. 
It would be a shame to miss it as CSS 3 adds many features to CSS (twice as many compared with CSS 2.1!). This course will thus use CSS 3, which incorporates and complements most of the features of CSS 2.1.

The most complex work is carried out by web browsers: they have to read the CSS code and understand how to display the page.

Although Internet Explorer was the most common browser at the start of the 2000s, the way it managed CSS remained mediocre (if not downright bad) for a long time. This was in the heyday of version 6 (IE6), which is unfortunately still used today by a small proportion of users (fortunately, this proportion is decreasing).

Since then, many browsers have come on the scene and have given Internet Explorer a rocky ride: Mozilla Firefox of course, but also Google Chrome. And not to mention the success of Macs and iPhones with their Safari browser. This prompted Microsoft to respond and publish (after a long period of inactivity) IE 7, IE 8 and then IE 9. There is already talk of IE 10.

Well, your history lesson is nice but how does it concern me today?

What can we learn from all this? That browsers do not know all existing CSS properties. The older the browser, the less its knows about CSS features.

I'm going to show you in this course a number of features of CSS that do not necessarily work on older browsers. I can't avoid it, it's just the way it is: no browser has a complete knowledge of all CSS features in any case! If the browser does not know a CSS property, it at worst ignores it and does not format it, but it does not crash your page: it will thus still be readable.

I highly recommend you bookmark the www.caniuse.com and normansblog.dewebsites which provide tables showing the compatibility between HTML and CSS features in various browsers (and their different versions). In particular, take a look at the CSS compatibility tables of www.caniuse.com (next figure).

CSS compatibility tableCSS compatibility table

CSS compatibility table of caniuse.com

Where do we write the CSS?

You can choose as you can write code in CSS language in three different places:

  • in a file with the extension .css (most recommended method);

  • in the HTML file <head> header;

  • directly in the tags of the HTML file via a style attribute (least recommended method).

Although I'll describe all three of these methods, I can tell you now that the first one... is the best.

In a .css file (recommended)

As I just said, CSS code is most often written in a special file with the extension .css(unlike HTML files which have the extension .html). This is the most convenient and flexible method. It avoids mixing everything in a single file. I'm going to use this technique in the rest of this course.

Let's get started straight away! We're going to use the HTML file below:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.css" />
<title>First tests of CSS</title>
</head>
<body>
<h1>My super website</h1>
<p>Hello and welcome to my website!</p>
<p>My website is still a bit <em>empty</em>. But wait a while yet!</p>
</body>
</html>

Notice the content of line 5, <link rel="stylesheet" href="style.css" />: this is the line that indicates that this HTML file is associated with a file called style.css which does the formatting.

Save this file as any name you want (for example, page.html). Up to now, there's nothing special except for the new tag we've added.

Now create a new empty file in your text editor (for example, Notepad++) and copy this piece of CSS code (don't worry, I'll explain to you what this means later):

p
{
color: blue;
}

To activate the code coloring in Notepad++, choose the menu Langage > C > CSS.

Save the file giving it a name ending with .css, such as style.css. Place this .cssfile in the same folder as your .html file.

In Notepad++, you should see something similar to the next figure.

HTML and CSS files in Notepad++HTML and CSS files in Notepad++

In your file explorer, you should see them displayed side by side. The .html file on one side and the .css file on the other, as shown in the next figure.

HTML and CSS files in the file explorerHTML and CSS files in the file explorer

Now open your page .html file in your browser to test it, as you usually do. Just look, it's magic: your paragraphs are shown in blue, as in the next figure!

The text is written in blueThe text is written in blue

There is no need to open the style.css file directly in the browser. You just have to open the page.html file (which will automatically call the style.cssfile).

In the HTML file <head> header

There's another way of using CSS in your HTML files: this involves inserting the CSS code directly in a <style> tag inside the header <head>.

Here's how you can get exactly the same result with a single .html file containing the CSS code (lines 5 to 10):

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style>
p
{
color: blue;
}
</style>
<title>First tests of CSS</title>
</head>
<body>
<h1>My super website</h1>
<p>Hello and welcome to my website!</p>
<p>My website is still a bit <em>empty</em>. But wait a while yet!</p>
</body>
</html>

Test it, you'll see that the result is the same.

Directly in the tags (not recommended)

Last method, to be handled with care: you can add a style attribute to any tag. You insert your CSS code directly in this attribute:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>First tests of CSS</title>
</head>
<body>
<h1>My super website</h1>
<p style="color: blue;">Hello and welcome to my website!</p>
<p>My website is still a bit <em>empty</em>. But wait a while yet!</p>
</body>
</html>

This time, only the text of the first paragraph (line 11), containing the CSS code, will be colored blue (next figure).

The first paragraph is written in blueThe first paragraph is written in blue

Which method should you choose?

I think that the first method you recommend is more complicated than the other two! Why do you advise us to create two files? I was doing fine with just one .html file!

I strongly recommend you get used to working with the first method as it's the one used by most webmasters... Why?

For the time being, you perform your tests on a single HTML file. However, your website will later on include several HTML pages, right?
Just imagine: if you put the CSS code directly in the HTML file, you'll have to copy this code into all the HTML files of your website! And if you change your mind tomorrow and, for example, want your paragraphs written in red instead of blue, you'll have to change each HTML file one by one, as shown in the next figure.

The CSS code is repeated in each HTML fileThe CSS code is repeated in each HTML file

If you work with an external CSS file, you'll only have to write this instruction once for your entire website, as shown in the next figure.

The CSS code is given once and for all in a CSS fileThe CSS code is given once and for all in a CSS file

Applying a style: selecting a tag

Now that we know where to put the CSS code, let's have a closer look at it. I gave you a first bit of CSS code without explaining it:

p
{
color: blue;
}

CSS code like this contains three different items:

  • Tag names: you write the names of the tags the appearance of which you want to change. For example, if you want to change the appearance of all <p>paragraphs, you have to write p.

  • CSS properties: the page "style effects" are stored in properties. For example, the color property allows you to specify the text color, and the font-size property is used to specify the text size, etc. There are a lot of CSS properties and, as I already told you, I'm not going to make you learn them all by heart.

  • Values: for each CSS property, you have to specify a value. For the colorproperty, for example, you have to specify the color name. For the font-sizeproperty, specify the size you want, etc.

A CSS style sheet thus broadly speaking looks like this:

tag1
{
property1: value1;
property2: value2;
property3: value3;
}
tag2
{
property1: value1;
property2: value2;
property3: value3;
property4: value4;
}
tag3
{
property1: value1;
}

In this code snippet, you can see the tags, properties and values I've just mentioned.

As you can see, you write name of the tag (for example, h1) and include the properties and values you want inside braces. You can include as many properties as you want inside braces. Each property is followed by the "colon" (":" symbol) and then the corresponding value. Finally, each line ends with a semicolon ";".

I'm going to teach you about a number of properties in the following chapters. For the time being, we'll just change the color in the examples as an exercise.

The CSS code we've used so far:

p
{
color: blue;
}

… thus means: "I want all my paragraphs to be written in blue.". The result is shown in the next figure.

Paragraphs written in blueParagraphs written in blue

Try changing the name of the tag affected by the CSS code. For example, if I write h1, the title will be written in blue. Edit your style.css file like this:

h1
{
color: blue;
}

Now open your HTML page again (remember, it's the HTML page you open in the browser, not the CSS file!): you should see its title displayed in blue (next figure)!

Title written in blueTitle written in blue

Applying a style to several tags

Let's take the CSS code below:

h1
{
color: blue;
}
em
{
color: blue;
}

It means that our titles <h1> and our important texts <em> must be displayed in blue. However, it's a bit repetitive, don't you think?

Fortunately, there's a way in CSS to go faster if both tags have to have the same presentation. Simply combine the declaration, separating the tag names with a comma, like this:

h1, em
{
color: blue;
}

The result is shown in the next figure.

Title and important text written in blueTitle and important text written in blue

This means: "I want the text of my <h1> and <em> tags to be written in blue".

You can specify as many tags one after the other as you want.

Comments in CSS

Like in HTML, you can include comments. Comments are not displayed and are simply used to specify information intended for you, to find your way, for example, through a long CSS file.

And, as you will see, the HTML file is generally fairly short and the CSS sheet fairly long (if it contains all your website's style items, this is quite normal). Note that you can create several CSS files for your website if you feel the need to separate your CSS code somewhat (depending on the various sections in your website, for example).

What were we talking about, again? Ah yes, comments in CSS.

So, to include a comment, it's easy! Enter /* followed by your comment, then */ to complete your comment.
You can write comments on one or more lines. For example:

/*
style.css
---------
By Mathieu Nebra
*/
p
{
color: blue; /* The paragraphs will be blue */
}

I may use comments in the rest of the course to provide explanations within .cssfiles themselves.

Applying a style: class and id

What I've shown you so far still has a shortcoming: it means, for example, that ALL paragraphs will have the same presentation (in this case, they'll all be written in blue).
What do you have to do to make only some paragraphs be written in a different way? You could put the CSS code in a style attribute on the intended tag (this is the technique I showed you earlier), but as I said, this is not recommended (it's better to use an external CSS file).

To solve the problem, you can use these special attributes which work on all tags:

  • the class attribute ;

  • the id attribute.

Let's be clear about this from the start: the class and id attributes are virtually the same. There's only a small difference that I'll show you below.
For the time being, and to put it simply, we're only going to concern ourselves with the class attribute.

As I just told you, this is an attribute that can be put in any tag, whether title, paragraph, image, etc.

<h1 class=""> </h1>
<p class=""> </p>
<img class="" />

Yes, but what value do you include for the class attribute?

In fact, you have to enter a name that identifies the tag. Whatever you want, as long as the name starts with a letter.

For example, I'm going to associate the introduction class with my first paragraph (line 12):

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.css" />
<title>First tests of CSS</title>
</head>
<body>
<h1>My super website</h1>
<p class="introduction">Hello and welcome to my website!</p>
<p>My website is still a bit <em>empty</em>. But wait a while yet!</p>
</body>
</html>

Having done this, your paragraph is now identified. It has a name: introduction. You'll be able to reuse this name in the CSS file to say: "I only want the tags called 'introduction' to be displayed in blue".

To do this in CSS, enter the name of your class starting with a dot, as shown below:

.introduction
{
color: blue;
}

Test the result: only your paragraph called introduction will be displayed in blue (figure below)!

Only the first paragraph is displayed in blueOnly the first paragraph is displayed in blue

And what about the id attribute?

It works in exactly the same way as class, with one exception: it can only be used once in the code.

What's the point of this? Not all that much, to be honest. It would be useful to you if you use JavaScript later on to recognise certain tags. And we've already seen the idattribute in the chapter on links (to enter anchors). In practice, we'll only enter an idon items that are unique in the page, such as the logo:

<img src="images/logo.png" alt="Website logo" id="logo" />

If you use ids, when defining their properties in the CSS file, you have to put a hash character (#) in front of the id name:

#logo
{
/* Specify the CSS properties here */
}

Don't bother to test it, it works exactly like class.

If you get class and id mixed up, remember that two tags can have the same name with the attribute class. An id name, however, must be unique in the HTML page.

General purpose tags

You may sometimes need to apply a class (or an id) to some words that were originally not surrounded by tags.

Indeed, the problem with class is that it's an attribute. So you can only enter it on a tag. If, for example, I want to only change "welcome" in the paragraph below:

<p>Hello and welcome to my site!</p>

It would be easy to do if there was a tag around "welcome", but unfortunately there's not. Luckily, someone invented... the tag-which-has-no-purpose.

In fact, two so-called general purpose tags were invented, which have no special meaning (they don't specify that the word is important, for example). There's a small (but significant!) difference between these two tags:

  • <span> </span>: is an inline type tag, in other words a tag that is placed within a paragraph of text, to only select certain words. The <strong> and <em> are of the same family. This tag is thus used in the middle of a paragraph and is the tag we're going to use to color "welcome".

  • <div> </div>: is a blocktype tag, which surrounds a block of text. The <p><h1>, etc. are of the same family. These tags have something in common: they create a new "block" in the page and thus necessarily insert a line break. <div> is a tag frequently used in building a design, as we shall see later.

So for now, we'll instead use the tag <span>. You place it around "welcome", add a class to it (any name you want), create the CSS and that's it!

<p>Hello and <span class="heybuddy">welcome</span> to my website!</p>
.heybuddy
{
color: blue;
}

You can see the result in the figure below.

The word welcome is written in blueThe word welcome is written in blue

Applying a style: the advanced selectors

In CSS, the most difficult thing is to know how to target the text for which you want to change the formatting. To target (we say "select") the items of the page to changed, you use what are called selectors. You already used a few of them earlier on in this chapter, so let's summarize them to begin with.

The selectors you already know

These selectors, as we saw above, are by far the most commonly ones used. You should know them by heart. Let's start from the beginning:

p
{
}

... means "I want to change every paragraph". After that, it's up to you to say what you want to do to these paragraphs (write them in blue, for example).

We also saw:

h1, em
{
}

... which means "All titles and all important texts." We've selected two tags in one go.

And finally, we saw how to select specific tags to which we gave a name using the class and id attributes:

.class
{
}
#id
{
}

And you know what? There are dozens of other ways of targeting tags in CSS! We're not going to look at them all as there are a lot and some are complex, but here's what you can do to be more effective in CSS!

The advanced selectors

*: general purpose selector
*
{
}

Selects all tags without exception. It's called the general purpose selector.

A B: one tag within another
h3 em
{
}

Selects all <em> tags located inside a <h3> tag. Note that there's no comma between the two tag names.

Corresponding sample HTML code:

<h3>Title with <em>important text</em></h3>
A + B: a tag that follows another tag
h3 + p
{
}

Selects the first <p> tag located after a <h3> title.

Example:

<h3>Title</h3>
<p>Paragraph</p>
A[attribut]: a tag that has an attribute
a[title]
{
}

Selects all the <a> links that have a title attribute.

Example:

<a href="http://site.com" title="Tooltip">
A[attribute="Value"]: a tag, an attribute and an exact value
a[title="Click here"]
{
}

Ditto, but the attribute must also have the exact value "Click here".

Example:

<a href="http://site.com" title="Click here">
A[attribute*="Value"]: a tag, an attribute and a value
a[title*="here"]
{
}

Ditto, the attribute must this time contain the word "here" in its value (in any position).

Example:

<a href="http://site.com" title="Somewhere around here">

There are also other selectors!

I've only described a few CSS selectors here and there are many others. If you want a complete list, you can find out directly from the source: on the W3C website! It's very comprehensive.

We'll discover some of these other selectors later in this course!

Summing up

  • CSS is another language that complements HTML. Its role is to format your web page.

  • You need to be vigilant about the compatibility of browsers with some recent CSS3 features. When a browser does not know a formatting instruction, it simply ignores it.

  • You can write CSS code in several different places, the most advised way being to create a separate file with the extension .css (for example: style.css).

  • In CSS, you select which parts of the HTML page you want to edit and then change their presentation with CSS properties:

tag1
{
property1: value1;
property2: value2;
}
  • There are many ways of selecting the portion of the page you want to format. For example, you can target:

    • all the tags of the same type, just by entering their name (h1 for example);

    • some specific tags, which you have assigned names to using the attributes class or id (.classname or #idname) ;

    • only tags that are located in other tags (h3 em).

    • ...

Text formatting

Log in or subscribe for free to enjoy all this course has to offer!

We've now come to a chapter that should be of great interest to you.

No, "text formatting" has nothing to do with the destruction of all data on your hard disk! It simply means that the text appearance is going to be changed (or "formatted").

There's nothing particularly surprising: CSS is still involved and we're going to reuse what we learned in the previous chapter. We're going to work directly in the .css file we created.

This chapter will provide an opportunity to find out many CSS properties: we're going to see how to change the text size, change the font, align the text, etc.

Size

To change the text size, you use the CSS font-size property. But how do you specify the text size? This is where things get tough as several techniques are available to you:

  • Specify an absolute size: in pixels, inches or millimeters. Although this method is very accurate, it is advisable only to use it when absolutely necessary, as you may well specify a size too small for some readers.

  • Specify a relative size: as a percentage, "em" or "ex", this technique has the advantage of being more flexible. It can be adapted more easily to the size preferences of visitors.

An absolute size

To specify an absolute size, pixels are generally used. So for a text 16 pixels high, you have to write:

font-size: 16px;

The letters will have a size of 16 pixels, as shown in the figure below.

A 16-pixel high letterA 16-pixel high letter

Here's an example of how to use it (put this code in your .css file):

p
{
font-size: 14px; /* 14-pixel paragraphs */
}
h1
{
font-size: 40px; /* 40-pixel titles */
}

And the result is shown in the figure below.

Various text sizesVarious text sizes

If you want, you can also set sizes in centimeters or millimeters. Replace "px" by "cm" or "mm". These units are, however, less well suited to screens.

A relative value

This is the recommended method as the text then adapts more easily to the preferences of all visitors.

There are several ways to specify a relative value. You can, for example, write the size as words like this:

  • xx-small : tiny ;

  • x-small : very small ;

  • small : small ;

  • medium : medium ;

  • large : large ;

  • x-large : very large ;

  • xx-large : errr... huge.

You can try using these values in your CSS code:

p
{
font-size: small;
}
h1
{
font-size: large;
}

This technique has a drawback, however: there are only seven sizes available (as there are only seven names). Fortunately, there are other ways. My favourite technique is to specify the size in "em".

  • If you write 1em, the text has a normal size.

  • If you want to make the text larger, you can enter a value greater than 1, like 1.3em.

  • If you want to make the text smaller, enter a value less than 1, like 0.8em.

Careful : decimal numbers are written with a point, not a comma. For example, you must type « 1.4em » , not « 1,4em »!

Example:

p
{
font-size: 0.8em;
}
h1
{
font-size: 1.3em;
}

Other units are available. You can try "ex" (which works on the same principle as em but has a smaller base) and the percentage (80%, 130%, etc.).

Font

Ah... The font... This can be tricky.

Indeed, there's a problem: for a font to be displayed properly, all Internet users have to have it. If an Internet user doesn't have the same font as you, their browser will use a default font (a standard font) that may not be at all what you're expecting.

The good news is that since CSS 3, it is now possible to get the browser to automatically download a font. I'll explain how to do this in a second step.

Changing the font used

The CSS property that allows you to specify the font to use is font-family. You have to write the font name like this:

tag
{
font-family: font;
}

To avoid problems if the Internet user doesn't have the same font as you, however, several font names, separated by commas, are generally specified:

tag
{
font-family: font1, font2, font3, font4;
}

The browser will first try to use font1. If it doesn't have it, it will try font2. If it doesn't have it, it will go on to font3, and so on.
As a last resort, you generally specify serif, which corresponds to a default font (which only applies if no other font has been found).

There is also another default font called sans-serif. The difference between the two is that the sans-serif font doesn't have the small connecting tabs at the bottom of letters. Yes, it's subtle.

But what, you may ask, are the most common fonts that you have the "right" to use?
Here's a list of fonts that work well on most browsers:

  • Arial ;

  • Arial Black ;

  • Comic Sans MS ;

  • Courier New ;

  • Georgia ;

  • Impact ;

  • Times New Roman ;

  • Trebuchet MS ;

  • Verdana.

The figure below shows you what these fonts look like.

Various fontsVarious fonts

So, if I write:

p
{
font-family: Impact, "Arial Black", Arial, Verdana, sans-serif;
}

… this means: "Set the Impact font or if that's not found, Arial Black, otherwise Arial, or otherwise Verdana, or if none of these worked, set a standard font (sans-serif)".

In general, it's a good idea to specify a choice of three or four fonts (+ serif or sans-serif) to make sure that at least one of them is found on the visitor's computer.

If the font name includes spaces, I recommend you surround it with quotes, as I've done for "Arial Black".

Using a custom font with @font-face

I find the choice of fonts too limited.
How can I use my favourite font on my website?

For a long time, this was not possible. Now, with CSS3, there is fortunately a way of using any font on your website. This works well with most browsers.

But beware, there are a few hitches (otherwise it would be just too good to be true):

  • Your visitors' browser will have to automatically download the font file whose stored size may be 1 MB or more...

  • Most fonts are subject to copyright so it's not legal to use them on your website. Fortunately, there are websites like fontsquirrel.com and dafont.com that allow you to download a number of copyright-free fonts. In particular, I recommend fontsquirrel.com as it allows you to download ready to use packs for CSS 3.

  • There are several formats of font files and they do not work on all browsers.

Here are the existing font file formats that you need to know:

  • .ttfTrueType Font. Works with IE9 and all other browsers.

  • .eotEmbedded OpenType. Works with all versions of Internet Explorer only. This is a proprietary format, produced by Microsoft.

  • .otfOpenType Font. Does not work with Internet Explorer.

  • .svgSVG Font. The only format supported on iPhones and iPads for the time being.

  • .woffWeb Open Font Format. New format designed for the Web, which works with IE9 and all other browsers.

To define a new font in CSS, you have to declare it like this:

@font-face {
font-family: 'MySuperFont';
src: url('MySuperFont.eot');
}

The font file (in this case MySuperFont.eot) must then be located in the same folder as the CSS file (or in a subfolder, if you use a relative path).

I thought there were several font formats?

Yes, and furthermore .eot only work in Internet Explorer. The ideal solution is to provide several formats for the font: the browser will download the one it can read. Here's how to specify several formats:

@font-face {
font-family: 'MySuperFont';
src: url('MySuperFont.eot') format('eot'),
url('MySuperFont.woff') format('woff'),
url('MySuperFont.ttf') format('truetype'),
url('MySuperFont.svg') format('svg');
}

To test how this works, I suggest you download a font from Font Squirrel, for example Learning Curve Pro. Click "@font-face Kit", which will allow you to download a ready to use kit with all the formats for this font.

Your CSS file will in the end look like this:

@font-face { /* Define a new font called LearningCurveProRegular */
font-family: 'LearningCurveProRegular';
src: url('LearningCurve_OT-webfont.eot');
src: url('LearningCurve_OT-webfont.eot?#iefix') format('embedded-opentype'),
url('LearningCurve_OT-webfont.woff') format('woff'),
url('LearningCurve_OT-webfont.ttf') format('truetype'),
url('LearningCurve_OT-webfont.svg#LearningCurveProRegular') format('svg');
}
h1 /* Use the font that you've just specified for the titles */
{
font-family: 'LearningCurveProRegular', Arial, serif;
}

The first (large) @font-face section defines a new font name that can be used in the CSS file. We then use this font name with the font-family property, that we know about, to change the appearance of the titles <h1>. You can see the result in the figure below.

Display of a customized fontDisplay of a customized font

You'll notice a few quirks in the CSS generated by the Font Squirrel website. The aim is to provide a workaround for certain bugs in Internet Explorer as older versions do not understand when several formats are defined. This explains the use of a ?#iefix in the code.

Italic, bold, underlined…

CSS has a series of standard text formatting properties. We're going find out here how to display text in bold, italic, underline, etc. and in doing so we're going to see it's even possible to make it blink!

Setting to italics

Hang on a bit! I thought that the <em>  tag was used to display text in italics?!

I never said that.
If you have any doubts, go back to the previous chapters, but I never said that the <em> tag was used to set text to italics (as in the same way, I never said that <strong> was used to make text bold).

<em>, get it firmly into your head, is intended to emphasize words. This means that the words it surrounds are fairly important.
To represent this importance, most browsers choose to display the text in italics, but it's not compulsory.

CSS, for its part, actually allows you to say: "I want this text to be in italics". For example, there's nothing stopping you from deciding to put all your titles in italics.

Specifically, to set text to italics in CSS, you use font-style which can take three values:

  • italic: the text will be set to italics.

  • oblique: the text will be displayed obliquely (letters are tilted and the result is slightly different from actual italics).

  • normal: the text will displayed in normal font (as default). This allows you to cancel italics. If you want the text between <em> to be no longer in italics, for example, you would write:

em
{
font-style: normal;
}

So in the example below, I've used font-style to italicize all my titles <h2>:

h2
{
font-style: italic;
}

Bolding

So what if we go on to bolding?
There again, remember that it's not <strong> that bolds the text (its purpose is to indicate that the text is important, and as a result the browser usually displays text in bold). In CSS, you can apply bolding to titles, some whole paragraphs, etc. It's up to you.

The CSS property to bold is font-weight and takes the following values:

  • bold: the text will be in bold;

  • normal: the text will displayed normally (as default).

Here's an example of how to write titles in bold:

h1
{
font-weight: bold;
}

Underlining and other decorations

The associated CSS property is aptly named: text-decoration. It allows you to underline text, among other things, but not just this. Here are the various it can take:

  • underline: underlined.

  • line-through: struck through.

  • overline: line above.

  • blink: blinking. Doesn't work in most browsers.

  • none: normal (as default).

This CSS code will allow you to test the effects of text-decoration using underline:

h1
{
text-decoration: underline;
}

And the result is shown in the figure below.

Formatting textFormatting text

Alignment

The CSS language lets you set all known text alignments: left, centered, right and justified.

It's quite straightforward. You use the text-align property and specify the desired alignment:

  • left: the text will be left-aligned (this is the default setting).

  • center: the text will be centered.

  • right: the text will be right-aligned.

  • justify: the text will be "justified". Justifying text makes it take up the whole possible width without leaving any white space at the ends of lines. Newspaper articles, for example, are always justified.

Take a look at the various alignments in this example:

h1
{
text-align: center;
}
p
{
text-align: justify;
}
.signature
{
text-align: right;
}

The result is shown in the figure below.

Text alignmentsText alignments

You can't change the alignment of text of an inline tag (such as <span>, <a>, <em>, <strong>…). Alignment only works on block (<p>, <div>, <h1>, <h2>, etc.) type tags, which is logical enough when you think about it: you can't change the alignment of a few words in the middle of a paragraph!
So in general, it's the whole paragraph you have to align.

Floating items

CSS allows us to float an item around the text. This is also called "wrapping".

To give you a good idea of what we're talking about, the figure below shows what we're going to learn to do.

A floating image surround by textA floating image surround by text

I guess that the burning question that's now on your mind is: "But what's the magical property that makes things float?".
The answer is... float. This property can take two very simple values:

  • left: the item will float on the left.

  • right: the item will float on the right! Yes, well done.

Floating items are very simple to use:

  1. You just apply a float to a tag.

  2. Then you continue to write the text following on normally.

You can use the float property on both block and inline tags. It is common to float an image for text to be wrapped round it, as in the previous example.

Making an image float

Here, we're going to learn how to make an image float. Here's the HTML code that we have to enter first:

<p><img src="flash.gif" class="floatingimage" alt="Floating image" /> This is a normal paragraph text, written after the image wrapped around it as the image is floating.</p>

You have to first place the floating item in the HTML code. If you place the image after the paragraph, the effect won't work.

Here's the only piece of CSS code that you have to type, which makes the image float on the left:

.floatingimage
{
float: left;
}

Try and make the image float on the right, it's dead easy: just specify the right value and there you are!

Stopping a floating effect

When you place floating image, the text wraps around it. But, after while, what if you want the text to continue underneath the floating image? You could combine several <br /> tags in sequence but this wouldn't be very tidy or elegant...

We would basically like to obtain the same result as the figure below.

The text under the image ignores the float propertyThe text under the image ignores the float property

CSS actually has property that allows you to say: "Stop, this text should be below the floating item and not next to it." This is the property clear, which can take these three values:

  • left: the text continues below after a float: left;

  • right: the text continues below after a float: right;

  • both: the text continues below, whether either after a float: left; or after a float: right;.

To simplify, we're always going to use the clear: both, which works after a float to the left and after a float to the right (so it works every time). To illustrate how it works, we're going to take the following HTML code:

<p><img src="flash.gif" class="floatingimage" alt="Floating image" /></p>
<p>This text is written next to the floating image.</p>
<p class="below">This text is written under the floating image.</p>

And this CSS code:

.floatingimage
{
float: left;
}
.below
{
clear: both;
}

And that's it.

You apply a clear: both; to the paragraph you want to see continue under the floating image and there you are!

Summing up

  • You change the text size with the CSS font-size property. You can specify the size in pixels (16px) in "em" (1.3em), as a percentage (110%), etc.

  • You change the text font with font-family. Be careful, only a few fonts are known by all computers. However, you can use a custom font with the @font-face instruction: this will force the browser to download the font of your choice.

  • There are many text formatting properties: font-style for italics, font-weightfor bolding, text-decoration for underlining, etc.

  • The text can be aligned with text-align.

  • An image can be wrapped ("surrounded") with text using float

Color and background

Log in or subscribe for free to enjoy all this course has to offer!

Let's continue our overview of the existing CSS properties. We're now going to look at the properties directly or indirectly related to the color. We going to see among other things:

  • how to change the text color;

  • how to add a color or background image;

  • how to add shadows;

  • how to vary transparency levels.

CSS still has plenty of surprises in store!

Text color

Let's now turn to the vast topic of color.

How do you mean, "vast"?

You already know about the property used to change the text color: it's color. We're going to look at the various ways of specifying color, as there are several.

Specifying the color name

The most simple and most convenient way to choose a color is to type its name.
The only drawback with this method is that there are only sixteen so-called "standard" colors. Although there are other informal colors, I won't bother showing them to you as they don't necessarily work the same way in all browsers.

The next figure shows the sixteen colors you can use by simply typing their name.

The sixteen color names that can be used in CSSThe sixteen color names that can be used in CSS

To change the color of all the titles to brown, you would thus enter:

h1
{
color: maroon;
}

You can see the result in the next figure.

The title is written in brownThe title is written in brown

Hexadecimal notation

But sixteen colors is all the same a bit limited when you consider that most monitors can display sixteen million.
On the other hand, mind you, if you had to give a name to each of the sixteen million colors...

Fortunately, there are several ways in CSS to choose a color from all the existing ones. The first way I'll show you is the hexadecimal notation. Although it is commonly used on the Web, there's also another method that we're going to see later.

This is what a color name in hexadecimal looks like: #FF5A28. Simply put, it's a combination of letters and numbers that specify a color.
You should always start by writing a hash character (#) followed by six letters or digits from 0 to 9 and A to F.
These letters or numbers work in pairs. The first two digits specify the quantity of red, the next two the quantity of green and the last two the quantity of blue. By mixing these quantities (which are the color's Red-Green-Blue components), you can get the color you want.

Thus, #000000 corresponds to black and #FFFFFF to white. But don't now ask me what combination to use to produce the "sunset" orange color as I have absolutely no idea.

Some drawing software programs such as Photoshop, Gimp and Paint.NET, let you specify the colors in hexadecimal. You can then easily copy and paste the hexadecimal code of a color in your CSS file.

Here, for example, is how you apply white to paragraphs in hexadecimal:

p
{
color: #FFFFFF;
}

Note that there is a shorthand notation: you can write a color with only three characters. For example: #FA3 is equivalent to writing #FFAA33.

The RGB method

What does RGB mean? Red-Green-Blue, which is abbreviated as "RGB". As with the hexadecimal notation, to choose a color, you have to define a quantity of red, green and blue.

This odd story about quantities of red-green-blue again?

Yes, but in this case you'll see that it's much more practical and with a simple drawing program such as Paint, you can find the color you want. Here are the steps to be followed:

  1. Start the Paint program from the Start menu.

  2. Go to the Edit colors section, as shown in the next figure.

  3. A window opens. In the box that appears on the right, move the sliders to select the color you want. Suppose you have a mad desire to write your titles <h1> in pink (only supposing). Select the color in the window, as shown in the next figure.

  4. Note the corresponding quantities of Red-Green-Blue indicated at the bottom right of the window (in this case 240-96-204). Enter these values in the same order in the CSS file, as shown in the code below.

p
{
color: rgb(240,96,204);
}
Changing colors in PaintChanging colors in PaintSelecting a color in PaintSelecting a color in Paint

As you could see in the example, to use the RGB method, you have to type rgb(Red, Green, Blue) replacing "Red, Green, Blue" by the corresponding numbers. For information, these quantities are always between 0 and 255.

Background color

To specify a background color, use the CSS background-color property. This is used in the same way as the color property, in other words, you can type the name of a color, enter it in hexadecimal notation or again use the RGB method.

To specify the web page background color, you have to work with the <body> tag. Indeed, <body> corresponds to the whole web page, so by changing its background color you'll change the color background of the page.

Look very carefully at this CSS file:

/* We're working with the body tag, and so with the WHOLE page */
body
{
background-color: black; /* The page background will be black */
color: white; /* The page text will be white */
}

The result of this code can be seen in the next figure.

White text on a black backgroundWhite text on a black background

But you asked for the text of the <body> tag to be written in white, and all the <p> paragraphs and <h1>titles took this color. Why is that?

Indeed, I wanted to take this opportunity to talk to you about this. This is known as inheritance. But I can reassure you right now, nobody died.

CSS and inheritance

In CSS, if you apply a style to a tag, all the tags that are inside will take the same style.

It's actually easy to understand and intuitive. As you know, the <body> tag contains among others the <p> paragraph and <h1> title tags.

If I apply a black background color and a white text color to the <body> tag, all my titles and paragraphs will also have a black background and white text... This phenomenon is called inheritance: the tags that are inside another tag are said to "inherit" its properties.

This also accounts for the name "CSS" which means "Cascading Style Sheets". CSS properties are inherited in cascade: if you give a style to an item, all the sub-items will have the same style.

This means that ALL the text of my web page will necessarily be in white?

No, not necessarily. If you say later on that you want your titles to be in red, this style will take precedence and your titles will thus be in red. However, if you don't specify anything in particular (as we did earlier), then your titles will inherit the white color.
Let's be clear, this doesn't just work for the color alone. All CSS properties are inherited: for example, you can assign bold in the <body> tag and all your titles and paragraphs will be in bold.

Example of inheritance with the <mark> tag

People tend to think that they can only change the background color of the page. This is not so: you can change the background of any item: your titles, your paragraphs, certain words, etc. In this case, they will appear highlighted (as if marked with a marker pen).

For example, do you remember the <mark> tag which is used to highlight certain words? Let's use it again here:

<h1>Who turned off the lights?</h1>
<p>Brr, it's all black on this website; it's a rather <mark>disturbing</mark> atmosphere don't you think?</p>

As default, the text appears on a yellow background. You can change this behaviour in CSS:

body
{
background-color: black;
color: white;
}
mark
{
/* The background color overrides the color of the whole page */
background-color: red;
color: black;
}

The red background color applies to the text of the <mark> tag. Indeed, even if the background of the page is black, it is the CSS property of the most specific item that has priority (next figure).

A red highlighted text on a black backgroundA red highlighted text on a black background

The same principle applies to all HTML tags and all CSS properties! If you say:

  • my paragraphs have a size of 1.2 em;

  • my important texts (<strong>) have a size of 1.4 em

... you might think that there would be a conflict. If the important text is part of a paragraph, what size should it be given? 1.2 em or 1.4 em? CSS decides that the most specific declaration takes precedence: as <strong> corresponds to a more specific item than paragraphs, the text will be written in 1.4 em.

Background images

In the following examples, I'm going to change the background image of the page. However, as for the background color, don't forget that the background image does not necessarily apply to the whole page. You can also put a background image behind titles, paragraphs, etc.

Applying a background image

The property used to specify a background image is background-image. As a value, you have to specify url("nom_de_l_image.png"). For example:

body
{
background-image: url("snow.png");
}

Which gives result shown in the next figure.

A background image on the pageA background image on the page

Of course, your background is not necessarily in PNG, but can also be in JPEG or GIF format.
The address indicating the location of the background image can be written as absolute address (http://…) or as a relative address (fond.png).

Be careful when you write a relative address in the CSS file! The address of the image must be specified relative to the .css file and not relative to .html file. To simplify things, I advise you to place the background image in the same folder as the .css file (or in a sub-folder).

Options for the background image

The background-image property that we've just seen can be supplemented by several other properties that allow the behavior of the background image to be changed.

background-attachment: attaching the background

The CSS background-attachment property is used to "attach" the background. The effect obtained is interesting as you can now see the text "slide" over the background. Two values are available:

  • fixed: the background image remains fixed;

  • scroll: the background image scrolls with the text (default).

body
{
background-image: url("snow.png");
background-attachment: fixed; /* The background will remain fixed */
}
background-repeat: background repetition

As default, the background image is repeated in a mosaic pattern. You can change this with the property background-repeat:

  • no-repeat: the background will not be repeated. The image will be unique on the page.

  • repeat-x: the bottom will be repeated only on the first line, horizontally.

  • repeat-y: the bottom will be repeated only on the first column, vertically.

  • repeat: the background will be repeated in a mosaic pattern (default).

Example of use:

body
{
background-image: url("sun.png");
background-repeat: no-repeat;
}
background-position: background position

You can specify the required position of the background image with background-position. This property is only useful if it is combined with background-repeat: no-repeat; (a background that does not repeat).

You have to enter two values in pixels for background-position to specify the background position relative to the top left corner of the page (or paragraph, if you apply the background to a paragraph). So if you enter:

background-position: 30px 50px;

... your background will be placed 30 pixels from the left and 50 pixels from the top. It is also possible to use these values:

  • top: at the top;

  • bottom: at the bottom;

  • left: to the left;

  • center: centered;

  • right: to the right.

These words can be combined. For example, to align an image at the top right, you would type:

background-position: top right;

So if I want to display a sun as a background image (next figure), just once (no-repeat), always visible (fixed) and positioned at the top right (top right), I would write this:

body
{
background-image: url("sun.png");
background-attachment: fixed; /* The background will remain fixed */
background-repeat: no-repeat; /* The background won't be repeated */
background-position: top right; /* The background will be displayed at the top right */
}
A sun as a background image in the top right cornerA sun as a background image in the top right corner

Combining properties

If you use a lot of properties in relation to the background (as is the case in the last example), you can use a sort of "super-property" called background whose value can combine several previously seen properties: background-imagebackground-repeatbackground-attachment and background-position.

We can thus simply write:

body
{
background: url("sun.png") fixed no-repeat top right;
}

This is the first "super-property" that I'm showing you, but there will be others. You should know the following:

  • The order of the values doesn't matter. You can combine values in any order.

  • You don't have to enter all the values. So if you don't want to enter fixed, you can remove it without any problem.

Several background images

Since CSS3, you can assign several background images to an item. To do this, simply separate the declarations by a comma, like this:

body
{
background: url("sun.png") fixed no-repeat top right, url("snow.png") fixed;
}

The first image of this list will be placed on top of the others (figure below). So beware, the image declaration order is important: if you reverse the sun and the snow in the CSS code above, you'll no longer see the sun!

Multiple background imagesMultiple background images

Note that multiple background images work on all browsers except older versions of Internet Explorer, which only recognize this feature as of version 9 (IE9).

One last thing before finishing with background images: In all these examples, I've applied a background to the whole page (body). However, this should not make you forget that you can apply a background to any item (a title, a paragraph, some words in a paragraph, etc.).
So for practice, I advise you to try to apply a background to your titles or paragraphs. If you have a bit of talent (unlike me), you'll no doubt be able to make your web page look quite nice.

Transparency

CSS allows us to very easily vary the transparency levels of items! To do this, we'll use CSS3 features: the opacity property and RGBa notation.

The opacity property

The very simple opacity property is used to specify the opacity level (which the reverse of transparency).

  • With a value of 1, the item will be completely opaque: this is the default behavior.

  • With a value of 0, the item will be completely transparent.

So you have to choose a value between 0 and 1. With a value of 0.6, your item will thus be 60% opaque ... and you'll be able to see through it!

Here's how it can be used:

p
{
opacity: 0.6;
}

Here's an example that will give you an idea of transparency. You can see the result in the next figure.

body
{
background: url('snow.png');
}
p
{
background-color: black;
color: white;
opacity: 0.3;
}
A transparent paragraphA transparent paragraph

Note that transparency works on all browsers, including Internet Explorer as of IE9 upwards.

If you apply the opacity property to an item of the page, all the content of this item will be made transparent (even images, other blocks inside, etc.). If you just want to make the background color transparent, it's best to use the RGBa notation that we're going to find out about.

The RGBa notation

CSS3 provides us with another way to vary the transparency: the RGBa notation. This is, in fact, the RGB notation we saw before, but with a fourth setting: the transparency level (called "alpha channel"). With a value of 1, the background is completely opaque in the same way as above. With a value of less than 1, it's transparent.

p
{
background-color: rgba(255, 0, 0, 0.5); /* Red, semi-transparent background */
}

It's as simple as that. You can get exactly the same effect as with opacity just using the RGBa notation. Give it a try!

This notation is known by all newer browsers, including Internet Explorer (as of IE9 upwards). For older browsers, it is recommended to specify the conventional RGB notation as well as RGBa.
So although for these browsers, the background will not be transparent, at least there will be a background color.

p
{
background-color: rgb(255,0,0); /* For older browsers */
background-color: rgba(255,0,0,0.5); /* For newer browsers */
}

Summing up

  • You change the text color with the color property, and the background color with background-color.

  • You can specify a color by enter its name (black, for example), in hexadecimal form (#FFC8D3) or in RGB notation (rgb(250,25,118)).

  • You can add a background image with background-image. You can choose to attach the background image, display it as a mosaic pattern or not, and even position it anywhere on the page.

  • You can make a portion of the page transparent with the opacity property or with the RGBa notation (same as the RGB notation, with a fourth value indicating the transparency level).

Borders and shadowing

Log in or subscribe for free to enjoy all this course has to offer!

New chapter, new set of CSS properties. Here, we're going to look at the borders and shadowing effects that can be applied both to the text and the blocks making up our page.

In particular, we're going to reuse our knowledge of colors to choose the color of our borders and shadowing.

Ready to be surprised again?

Standard borders

CSS provides you with a wide selection of borders to decorate your page. Many CSS properties allow you to change the appearance of your borders: border-widthborder-colorborder-style

To get to the point, I intend to directly use the border super-property which includes all these properties. Do you remember the background super-property? It works on the same principle: we're going to be able to combine several values.

For border, you can use up to three values to change the border appearance:

  • The width: specify the width of your border. Enter a value in pixels (such as 2px).

  • The color: this is your border's color. As we learned, use either a color name (blackred, etc.) or a hexadecimal value (#FF0000) or an RGB value (rgb(198, 212, 37)).

  • The border type: several options are available. Your border can be a single solid line, a dotted line or a dashed line, etc. Here are the available values:

    • none: no border (default);

    • solid: a single solid line;

    • dotted: a dotted line;

    • dashed: a dashed line;

    • double: a double border;

    • groove: a grooved line;

    • ridge: a ridged line;

    • inset: global inset 3D effect;

    • outset: global outset 3D effect.

So to obtain a blue border as a dashed line 3 pixels thick around my titles, I would enter:

h1
{
border: 3px blue dashed;
}

The next figure shows the various border styles you can use.

Various border stylesVarious border styles

At the top, on the right, on the left, at the bottom...

Who said you have to apply the same border to all four sides of your item?
Nonsense, if you want to put different borders depending on the side (top, bottom, left or right), you can do so with no problem. In this case, you have to use these four properties:

  • border-top: top border;

  • border-bottom: bottom border;

  • border-left: left border;

  • border-right: right border.

There are also equivalents for setting each detail of the border if you want: border-top-width to change the thickness of the top border, border-top-color for the top color etc.

They are also super-properties which work like border but thus only apply to a single side.

To add a border to the left and right of paragraphs only, we would thus enter:

p
{
border-left: 2px solid black;
border-right: 2px solid black;
}

You can change the borders of any type of item on the page. We've done it here on paragraphs but you can also change the border of images, important texts such as <strong> etc.

Rounded borders

Rounded borders are a bit like the Holy Grail webmasters have been waiting for since the last millennia (or so it seems). Since the arrival of CSS3, it's now possible to create them easily!

The border-radius property will allow us to easily round the corners of any item. Simply specify the size ("importance") of the radius in pixels:

p
{
border-radius: 10px;
}

The radius is seen in particular if the item has borders, as shown in the figure below.

Rounded bordersRounded borders

... or if it has a background color, as in the next figure.

A background with rounded cornersA background with rounded corners

You can also specify the radius shape for each corner. In this case, specify four values:

p
{
border-radius: 10px 5px 10px 5px;
}

The values correspond to the following corners in the order indicated:

  1. top left;

  2. top right;

  3. bottom right;

  4. bottom left.

Finally, you can refine the rounding of your corners by creating elliptic curves as in the next figure. In this case, you have to specify two values separated by a / character (slash). To see the effect, it's certainly best to test it:

p
{
border-radius: 20px / 10px;
}
Elliptical rounded bordersElliptical rounded borders

Rounded edges work with all newer browsers, including Internet Explorer as of version 9 (IE9) upwards.
For older versions of Mozilla Firefox, Chrome and Safari, so-called "vendor prefixes" had to be used, in other words, you had to write various versions of the property (-moz-border-radius for Firefox, -webkit-border-radius for Safari, etc.) in the CSS code. This is fortunately now no longer necessary, unless you want to support the older versions of these browsers.

Shadowing

Shadows are included in the latest innovations provided by CSS3. You now need just a single line of CSS to add shadows to a page!

Here we're going to find out about two types of shadows:

  • box shadows;

  • text shadows.

box-shadow: box shadows

The box-shadow property applies to the whole block and takes four values in the following order:

  1. the shadow horizontal offset;

  2. the shadow vertical offset;

  3. the toning down;

  4. the shadow color.

For example, for a black, 6-pixel shadow, with no toning down, we would enter:

p
{
box-shadow: 6px 6px 0px black;
}

The result this would give is shown in the next figure (I added a border to the paragraph to show the effect better).

A shadow under the paragraphA shadow under the paragraph

Let's tone down the shadow using the third setting (figure below). The toning down can be low (less than the offset), normal (equal to the offset) or high (greater than the offset). Let's try a normal offset:

p
{
box-shadow: 6px 6px 6px black;
}
A rounded shadow under the paragraphA rounded shadow under the paragraph

You can also add an optional fourth value: inset. In this case, the shadow will be placed inside the block, to give an inset effect:

p
{
box-shadow: 6px 6px 6px black inset;
}

I'll leave you to try it to see the result.

The box-shadow property works on all newer browsers, including IE9. For some browsers, especially mobile browsers, a prefix still has to be added. You thus have to enter a -webkit-box-shadow version for this to work on Android and iOS browsers.

text-shadow: text shadow

With text-shadow, you can add a shadow directly to the letters of your text! The values work in exactly the same way as box-shadow: offset, toning down and color.

p
{
text-shadow: 2px 2px 4px black;
}

The result is shown in the next figure.

Shadowed textShadowed text

This property is recognized by all newer browsers except Internet Explorer, which only recognizes it from version IE10 up.

Summing up

  • You can apply a border to an item using the border property. You have to specify the border width, color and type (solid line, dotted line, etc.).

  • You can round the borders using border-radius.

  • You can add a shadow to text blocks using box-shadow. You have to specify the shadow vertical and horizontal offset, it toning down level and its color.

  • The text can also be given a shadow using text-shadow.

Creating dynamic appearances

Log in or subscribe for free to enjoy all this course has to offer!

This is one of its strong points: CSS also allows us to change the appearance of items dynamically, in other words, items can change shape once the page has been loaded. We're going to use one of CSS' powerful features: pseudo-formats.

In this chapter, we're going to see how to change the appearance:

  • when hovering;

  • on clicking;

  • on focusing (selected item);

  • when a link has been visited.

You'll see that CSS still has plenty of surprises in store!

When hovering

In this chapter, we're going to find out about several CSS pseudo-formats. The first I'm going to show you is called :hover. Like all the other pseudo-formats we're going to see, it's information that is added after the tag name (or class) in the CSS, like this:

a:hover
{
}

:hover can be interpreted as: "When the mouse pointer is over the link" (when you point to it).

From there, it's up to you to define the appearance that links take when you click on them. Give a free rein to your imagination, there's no limit.

Here's an example of link presentation, but feel free to invent your own:

a /* Default links (when not hovered over) */
{
text-decoration: none;
color: red;
font-style: italic;
}
a:hover /* Appearance of links when hovered over */
{
text-decoration: underline;
color: green;
}

We've defined two versions of styles for links:

  • for default links (when not hovered over);

  • for links when hovered over.

The result is shown in the next figure.

Change of appearance when hovered over with the mouseChange of appearance when hovered over with the mouse

Nice, isn't it?

While it's often used on links, you can change the appearance of any item. For example, you can change the appearance of paragraphs when you point to them:

p:hover /* When you point to a paragraph */
{
}

On clicking and selecting

You can interact even more finely in CSS. We're going to see that we can change the appearance of items when clicked and when selected!

:active: when clicked

The :active pseudo-format allows you to apply a particular style when you click. In practice, it's only used on links.

The link won't keep this appearance for very long: in fact, the change takes effect when the mouse button is pressed. Clearly, this won't necessarily always be very visible.

You can, for example, change the link's background color when it's clicked:

a:active /* When the visitor clicks the link */
{
background-color: #FFCC66;
}

:focus: when the item is selected

In this case, it's a bit different. The :focus pseudo-format applies a style when the item is selected.

In other words?

Once clicked, the link remains "selected" (it has a little dotted border around it). That's the selection.

This pseudo-format can be applied to other HTML tags that we have not yet seen, such as form items.

Let's try it for now on links:

a:focus /* When the visitor selects the link */
{
background-color: #FFCC66;
}

In Google Chrome and Safari, the effect is only seen when you press the Tabkey.

When the link has already been visited

You can apply a style to a link to a page that has already been visited. As default, the browser changes the link color to a pretty ugly purple (in my view, at least!).

You can change this appearance with :visited. In practice, for visited links, you can't change a lot apart from the color (next figure).

a:visited /* When the visitor has already seen the page concerned */
{
color: #AAA; /* Apply a grey color */
}
Visited links in greyVisited links in grey

If you don't want already visited links to be colored in a different way, you have to apply the same color to them as normal links. Many websites do this. One notable exception: Google... which is quite handy, as you can see in the search results whether or not you've already visited the websites found by Google.

Summing up

  • In CSS, you can change the appearance of certain sections dynamically, after the page is loaded, when certain events occur. For this purpose, pseudo-formats are used.

  • The :hover pseudo-format is used to change the appearance on hovering (for example: a:hover to change the appearance of links when the mouse hovers over them).

  • The :active pseudo-format changes the appearance of links when you click on them, :visited when a link has already been visited.

  • The :focus pseudo-format is used to change the appearance of a selected item.

Congrats, you made it to the end of this part! Don't forget to complete your exercises before moving on to the next part. You will find the links to the quizz and the assessment of this second part in the course outline. Good luck!



Comments