CSS. Unidad 2. Estilos de texto y fuente de letra.

Introduction

Here we’ll go through all the basic fundamentals of text/font styling in detail, including setting font weight, family and style, font shorthand, text alignment and other effects, and line and letter spacing.

What is involved in styling text in CSS?

The CSS properties used to style text generally fall into two categories, which we’ll look at separately in this unit:

  • Font styles: Properties that affect the font that is applied to the text, affecting what font is applied, how big it is, whether it is bold, italic, etc.
  • Text layout styles: Properties that affect the spacing and other layout features of the text, allowing manipulation of, for example, the space between lines and letters, and how the text is aligned within the content box.

Bear in mind that the text inside an element is all affected as one single entity. You can’t select and style subsections of text unless you wrap them in an appropriate element (such as a <span> or <strong>, for example).

Font color

Let’s move straight on to look at properties for styling fonts. In this section we’ll apply some different CSS properties to the same HTML sample.

The color property sets the color of the foreground content of the selected elements (which is usually the text, but can also include a couple of other things, such as an underline or overline placed on text using the text-decoration property):

p {
  color: red;
}

Proposed exercise

Create a new web page made of 2 files: one HTML file with the code below, and another one with some CSS code to change the <h1> and <p> elements to any color you like. Do not forget to link the CSS file from the HTML file, and validate your code.

<h1>Tommy the cat</h1>

<p>Well I remember it as though it were a meal ago...</p>

<p>Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did.</p>

Font families

To set a different font on your text, you use the font-family property — this allows you to specify a font (or list of fonts) for the browser to apply to the selected elements. The browser will only apply a font if it is available on the machine the website is being accessed on; if not, it will just use a browser default font. A simple example looks like so:

p {
  font-family: arial;
}

This would make all paragraphs on a page adopt the arial font, which is found on any computer.

Default fonts

CSS defines five generic names for fonts:  serifsans-serifmonospacecursive and fantasy. Those are very generic and the exact font face used when using those generic names is up to each browser and can vary for each operating system they are running on. It represents a worst case scenario where the browser will try to do its best to provide at least a font that looks appropriate. serifsans-serif and monospace are quite predictable and should provide something reasonable. On the other hand, cursive and fantasy are less predictable and we recommend using them very carefully, testing as you go.

The five names are defined as follows (you will find below some examples about how they look like):

  • serif: Fonts that have serifs (the flourishes and other small details you see at the ends of the strokes in some typefaces).
  • sans-serif: Fonts that don’t have serifs.
  • monospace: Fonts where every character has the same width, typically used in code listings.
  • cursive: Fonts that are intended to emulate handwriting, with flowing, connected strokes.
  • fantasy: Fonts that are intended to be decorative.
  • This is serif
  • This is sans-serif
  • This is monospace
  • This is cursive
  • This is fantasy

Proposed exercise: Default fonts

Using the code of the previous exercise, copy and paste the paragraphs several times (5 in total) and define some classes to apply all default fonts (serif, sans-serif, monospace, cursive, fantasy). You must set a different font and color each time. Your source code and the result should look something like this:

HTML code:

<h1>Tommy the cat</h1>

<p class="serif">Well I remember it as though it were a meal ago...</p>
<p class="serif">Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did.</p>

...

<p class="fantasy">Well I remember it as though it were a meal ago...</p>
<p class="fantasy">Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did.</p>

CSS code:

.serif {
    font-family: serif;
    color: blue;
}

...

.fantasy {
    font-family: fantasy;
    color: green;
}

And the result:

Tommy the cat

Well I remember it as though it were a meal ago…

Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did.

Well I remember it as though it were a meal ago…

Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did.

Web safe fonts

Speaking of font availability, there are only a certain number of fonts that are generally available across all systems and can therefore be used without much worry. These are the so-called web safe fonts.

Most of the time, as web developers we want to have more specific control over the fonts used to display our text content. The problem is to find a way to know which font is available on the computer used to see our web pages. There is no way to know this in every case, but the web safe fonts are known to be available on nearly all instances of the most used operating systems (Windows, macOS, the most common Linux distributions, Android, and iOS).

The list of actual web safe fonts will change as operating systems evolve, but it’s reasonable to consider the following fonts web safe, at least for now (many of them have been popularized thanks to the Microsoft Core fonts for the Web initiative in the late 90s and early 2000s):

  • Arial (sans-serif)
  • Courier New (monospace)
  • Georgia (serif)
  • Times New Roman (serif)
  • Trebuchet MS (sans-serif)
  • Verdana (sans-serif)

Among various resources, the cssfontstack.com website maintains a list of web safe fonts available on Windows and macOS operating systems, which can help you make your decision about what you consider safe for your usage.

Proposed exercise: Main safe fonts

Create a new web page with a header (<h1>) and six other paragraphs (<p>) with any content you like, and set a different font for each of them (Arial, Courier New, Georgia, Times New Roman, Trebuchet MS, Verdana). You can also change the color of the text too.

Font names that have more than one word (like Trebuchet MS) need to be surrounded by quotes, for example:
font-family: "Trebuchet MS";

Font stacks

Since you can’t guarantee the availability of the fonts you want to use on your webpages (even a web font could fail for some reason), you can supply a font stack so that the browser has multiple fonts it can choose from. This simply involves a font-family value consisting of multiple font names separated by commas, e.g.

p {
  font-family: "Trebuchet MS", Verdana, sans-serif;
}

In such a case, the browser starts at the beginning of the list and looks to see if that font is available on the machine. If it is, it applies that font to the selected elements. If not, it moves on to the next font, and so on.

It is a good idea to provide a suitable generic font name at the end of the stack so that if none of the listed fonts are available, the browser can at least provide something approximately suitable. To emphasise this point, paragraphs are given the browser’s default serif font if no other option is available — which is usually Times New Roman — this is no good for a sans-serif font!

Proposed exercise: More safe fonts and font stacks

Create a new web page with a header and five other paragraphs with any content you like, and set a different font for each of them, but this time you cannot use any font used previously: you must select some other fonts from cssfontstack.com. Moreover, in this exercise you have to use font stacks to ensure at least one font is always available, and you can also change the color too. Finally, check your web page using several browsers from several devices and operating systems, to make sure that all fonts are shown.

If you are changing the color and the font family using font stacks, your CSS and HTML code should look like this:
.font-book {
  color: blue;
  font-family: "Book Antiqua", Arial, sans-serif;
}
<p class="font-book"> ... </p>

Using an online font service

Online font services generally store and serve fonts for you, so you don’t have to worry about the font availability, and generally you just need to insert a simple line or two of code into your site to make everything work. Examples include Adobe Fonts and Cloud.typography. Most of these services are subscription-based, with the notable exception of Google Fonts, a useful free service, especially for rapid testing work and writing demos.

Most of these services are easy to use, so we won’t cover them in great detail. Let’s have a quick look at Google fonts, so you can get the idea. These are the steps that you have to follow to use one or several of the fonts they provide:

  1. Go to Google Fonts.
  2. You may use the filters to display the kinds of fonts you like.
  3. To select a font family, click on it, and after that press the «+ Select this style» option on the right hand side.
  4. When you’ve chosen the font families, press the «View your selected families» icon at the top right corner of the page.
  5. In the resulting screen, you first need to copy the line of HTML code shown and paste it into the head of your HTML file. Put it above the existing <link> element, so that the font is imported before you try to use it in your CSS.
  6. You then need to copy the CSS declarations listed into your CSS as appropriate, to apply the custom fonts to your HTML.

Proposed exercise: Google fonts

Create a web page with ten paragraphs, each one using a different Google font.

For example, to use the Google fonts «Nerko One», «Permanent Marker» and «Rock Salt», your HTML code should look like this:
<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Web font example</title>
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Nerko+One&family=Permanent+Marker&family=Rock+Salt&display=swap">
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <h1>Web font example</h1>
    <p class="nerko">This is a text with Nerko One font</p>
    <p class="marker">This is a text with Permanent Marker font</p>
    <p class="rock">This is a text with Rock Salt</p>
  </body>
</html>

The CSS code inside your own file styles.css:

.nerko {
  font-family: 'Nerko One', cursive;
}
.marker {
  font-family: 'Permanent Marker', cursive;
}
.rock {
  font-family: 'Rock Salt', cursive;
}

And the result:

This is a text with Nerko One font

This is a text with Permanent Market font

This is a text with Rock Salt font

Font size

Font size (set with the font-size property) can take values measured in several units (such as percentages), however the most common units you’ll use to size text are:

  • px (pixels): The number of pixels high you want the text to be (this is an absolute unit).
  • em: 1 em is equal to the font size set on the parent element of the current element we are styling (more specifically, the width of a capital letter M contained inside the parent element.) This can become tricky to work out if you have a lot of nested elements with different font sizes set, but t is quite natural once you get used to it, and you can use em to size everything, not just text. You can have an entire website sized using em, which makes maintenance easy.
  • rem: These work just like em, except that 1 rem is equal to the font size set on the root element of the document (i.e. <html>), not the parent element. This makes doing the maths to work out your font sizes much easier, although if you want to support really old browsers, you might struggle (rem is not supported in Internet Explorer 8 and below).

Absolute size (pixels)

The easiest way to change the size of your text is setting a specific number of pixels. However, this might not be the best solution, since in case you want to increase (or decrease) the size of all text in your website, you should change each value manually (one time per each CSS rule). So, we are going ahead with a first exercise using pixels, but after that we will use a more convenient way in another exercise using relative values.

Proposed exercise: Absolute sizing with «px»

Create a new web page with at least 15 paragraphs of some text you like, and set the font size for each paragraph a bit larger each time. You must use pixels to set each font size.

Your source code and result should look like this (you may choose any class names, colors and sizes you like):
.ten {
  color: black;
  font-size: 10px;
}

.eleven {
  color: blue;
  font-size: 11px;
}

.twelve {
  color: green;
  font-size: 12px;
}

.thirteen {
  color: brown;
  font-size: 13px;
}

...
<p class="ten">This is a text with 10 px font size</p>
<p class="eleven">This is a text with 11 px font size</p>
<p class="twelve">This is a text with 12 px font size</p>
<p class="thirteen">This is a text with 13 px font size</p>
...

This is a text with 10 px font size

This is a text with 11 px font size

This is a text with 12 px font size

This is a text with 13 px font size

This is a text with 14 px font size

Relative size («em» and «rem»)

The font-size of an element is inherited from that element’s parent element. This all starts with the root element of the entire document  (<html>) the font-size of which is set to 16 px as standard across browsers. Any paragraph (or another element that doesn’t have a different size set by the browser) inside the root element will have a final size of 16 px. Other elements may have different default sizes, for example an <h1> element has a size of 2 em set by default, so it will have a final size of 32 px.

Things become more tricky when you start altering the font size of nested elements. For example, if you had an <article> element in your page, and set its font-size to 1.5 em (which would compute to 24 px final size), and then wanted the paragraphs inside the <article> elements to have a computed font size of 20 px, what em value would you use?

<!-- document base font-size is 16px -->
<article> <!-- If my font-size is 1.5em -->
  <p>My paragraph</p> <!-- How do I compute to 20px font-size? -->
</article>

You would need to set its em value to 20/24, or 0.83333333 em. The maths can be complicated, so you need to be careful about how you style things. It is best to use rem where you can, to keep things simple, and avoid setting the font-size of container elements where possible.

When sizing your text, it is usually a good idea to set the base font-size of the document to 10px, so that then the maths is a lot easier to work out (required (r)em values are then the pixel font size divided by 10, not 16). After doing that, you can easily size the different types of text in your document to what you want. Also it is a good idea to list all your font-size rulesets in a designated area in your stylesheet, so they are easy to find.

Proposed exercise: Relative sizing with «rem»

Create a new web page with at least 15 paragraphs of some text you like, and set the font size for each paragraph a bit larger each time. This time, you must use relative sizing to set each font size (for example, with «rem» units). When you finish writing your code, check the results using your browser, and set different values for the main size (inside the <html> element) and check that the size of all the paragraphs changes accordingly.

Your source code and result should look like this (you may choose any class names, colors and sizes you like):
html {
  color: black;
  font-size: 10px;
}

.eleven {
  color: blue;
  font-size: 1.1rem;
}

.twelve {
  color: green;
  font-size: 1.2rem;
}

.thirteen {
  color: olive;
  font-size: 1.3rem;
}

...
<p>This is a text with 1 rem font size</p>
<p class="eleven">This is a text with 1.1 rem font size</p>
<p class="twelve">This is a text with 1.2 rem font size</p>
<p class="thirteen">This is a text with 1.3 rem font size</p>
...

This is a text with 1 rem font size

This is a text with 1.1 rem font size

This is a text with 1.2 rem font size

This is a text with 1.3 rem font size

This is a text with 1.4 rem font size

Font style, font weight, text transform, and text decoration

CSS provides four common properties to alter the visual weight/emphasis of text:

  • font-style: Used to turn italic text on and off. Possible values are as follows (you’ll rarely use this, unless you want to turn some italic styling off for some reason):
    • normal: Sets the text to the normal font (turns existing italics off)
    • italic: Sets the text to use the italic version of the font if available; if not available, it will simulate italics with oblique instead.
    • oblique: Sets the text to use a simulated version of an italic font, created by slanting the normal version.
  • font-weight: Sets how bold the text is. This has many values available in case you have many font variants available (such as -light-normal-bold-extrabold-black, etc.), but realistically you’ll rarely use any of them except for normal and bold:
    • normalbold: Normal and bold font weight
    • lighterbolder: Sets the current element’s boldness to be one step lighter or heavier than its parent element’s boldness.
    • 100900: Numeric boldness values that provide finer grained control than the above keywords, if needed. 
  • text-transform: Allows you to set your font to be transformed. Values include:
    • none: Prevents any transformation.
    • uppercase: Transforms ALL TEXT TO CAPITALS.
    • lowercase: Transforms all text to lower case.
    • capitalize: Transforms all words to Have The First Letter Capitalized.
    • full-width: Transforms all glyphs to be written inside a fixed-width square, similar to a monospace font, allowing aligning of e.g. Latin characters along with Asian language glyphs (like Chinese, Japanese, Korean).
  • text-decoration: Sets/unsets text decorations on fonts (you’ll mainly use this to unset the default underline on links when styling them.) Available values are:
    • none: Unsets any text decorations already present.
    • underline: Underlines the text.
    • overline: Gives the text an overline.
    • line-through: Puts a strikethrough over the text.

You may use some combinations of the options above. For example:

p {
  font-weight: bold;
  text-transform: uppercase;
  text-decoration: line-through;
}

This an uppercase text with line through text decoration

You should also note that text-decoration can accept multiple values at once, if you want to add multiple decorations simultaneously, for example text-decoration: underline overline. Also note that text-decoration is a shorthand property for text-decoration-linetext-decoration-style, and text-decoration-color. You can use combinations of these property values to create interesting effects, for example:

p {
  font-weight: bold;
  text-transform: uppercase;
  text-decoration: line-through red wavy;
}

This a bold uppercase text with a text decoration of a red wavy line through

Proposed exercise: Style, weight, transform and decoration

Create a website with at least 15 paragraphs to show most of the values that can be used with font-style , font-weight , font-transform and font-decoration properties.

This is an example of the result you should get (you may choose your own combinations):

This is a normal text

This is an italic text

This is a bold text

This is an uppercase and italic text

This is a bold and uppercase text

This is a capitalized text with a weight of 500

This is a capitalized text with a weight of 600

This is a capitalized text with a weight of 700

This is a capitalized text with a weight of 800

This is a capitalized text with a weight of 900

This is an uppercase bold text with an orange line through decoration

This is an uppercase bold text with a blue line through decoration

This is a capitalized bold text with a wavy red line through

This is an uppercase bold text underlined and also with red line-through

Text drop shadows

You can apply drop shadows to your text using the text-shadow property. This takes up to four values, as shown in the example below:

text-shadow: 4px 4px 5px red;

The four properties are as follows:

  1. The horizontal offset of the shadow from the original text. This can take most available CSS length and size units, but you’ll most commonly use px. Positive values move the shadow right, and negative values left. This value has to be included.
  2. The vertical offset of the shadow from the original text; behaves basically just like the horizontal offset, except that it moves the shadow up/down, not left/right. This value has to be included.
  3. The blur radius. A higher value means the shadow is dispersed more widely. If this value is not included, it defaults to 0, which means no blur. This can take most available CSS length and size units.
  4. The base color of the shadow, which can take any CSS color unit. If not included, it defaults to currentColor, i.e. the shadow’s color is taken from the element’s color property.

You can also apply multiple shadows to the same text by including multiple shadow values separated by commas, for example:

text-shadow: 1px 1px 1px red,
             2px 2px 1px red;

Proposed exercise: Simple shadows

Create a website with at least 15 paragraphs with shadows, each one with different offsets and colors. You can also change any other properties you like, such as the font-family. You should use Google Fonts to ensure that everything is displayed in the right way for all the operating systems and browsers.

This is an example of the result you should get (you may choose your own combinations):

This is a white text with Permanent Marker font and 2 px offset black shadow with 5 px blur

This is a text with Permanent Marker font and 2 px offset yellow shadow without blur

This is a text with Permanent Marker font and 3 px offset yellow shadow with 5 px blur

This is a text with Nerko One font and 2 px offset orange shadow without blur

This is a text with Nerko One font and 2 px offset orange shadow with 5 px blur

This is a bold text with Rock Salt font and 2 px offset red shadow without blur

This is a bold text with Rock Salt font and 2 px offset red shadow with 5 px blur

Proposed exercise: Multiple shadows

Create a website with at least 10 paragraphs each one with multiple shadows and also different offsets and colors. You can also change any other properties you like, such as the font-family and font-size. You should use Google Fonts to ensure that everything is displayed in the right way for all the operating systems and browsers.

This is an example of the result you should get (you may choose your own combinations):

This is a bold white text with Sedgwick Ave font and 1 px offset red shadow and 3 px offset black shadow with 5 px blur

This is a bold text with Sedgwick Ave font and 2 px offset yellow shadow and also a 3 px offset blue shadow without blur

This is a bold text with Sedgwick Ave font and 3 px offset yellow shadow and also a 6 px offset blue shadow with 5 px blur

This is a text with Lakki Reddy font and 1 px offset orange shadow and also a 2 px offset red shadow without blur

This is a text with Lakki Reddy font and 3 px offset orange shadow and also a 6 px offset red shadow with 5 px blur

This is an orange bold text with Gloria Hallelujah font and 2 px offset red shadow and also a 4 px offset blue shadow without blur

This is an orange bold text with Gloria Hallelujah font and 3 px offset red shadow and also a 6 px blue shadow with 5 px blur

Text-alignment

The text-align property is used to control how text is aligned within its containing content box. The available values are as follows, and work in pretty much the same way as they do in a regular word processor application:

  • left: Left-justifies the text.
  • right: Right-justifies the text.
  • center: Centers the text.
  • justify: Makes the text spread out, varying the gaps in between the words so that all lines of text are the same width. You need to use this carefully, since sometimes it can look terrible, especially when applied to a paragraph with lots of long words in it. If you are going to use this, you should also think about using something else along with it, such as hyphens, to break some of the longer words across lines.

For example, you can center some text just by using the following CSS code:

text-align: center;

Proposed exercise: Alignment types

Create a web page with 4 headers and 4 paragraphs, each one with a different alignment type.

You can use any text you like, but keeping in mind that you must insert several lines to properly see how the alignment is done:

This is left alignment

Well I remember it as though it were a meal ago… Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator. Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did.

This is right alignment

Well I remember it as though it were a meal ago… Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator. Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did.

This is center alignment

Well I remember it as though it were a meal ago… Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator. Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did.

This is justify alignment

Well I remember it as though it were a meal ago… Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator. Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did.

Line height

The line-height property sets the height of each line of text. This can take most length and size units, but can also take a unitless value, which acts as a multiplier and is generally considered the best option (the font-size is multiplied to get the line-height). Body text generally looks nicer and is easier to read when the lines are spaced apart; the recommended line height is around 1.5 – 2 (double spaced.) So to set our lines of text to 1.6 times the height of the font, you’d use this:

line-height: 1.6;

Proposed exercise: Line heights

Create a web page with at least 3 headers and 3 paragraphs, each one with a different line height.

This text has 0.8 line height:

Well I remember it as though it were a meal ago… Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator. Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did.

This text has 1.2 line height:

Well I remember it as though it were a meal ago… Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator. Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did.

This text has 1.6 line height:

Well I remember it as though it were a meal ago… Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator. Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did.

Letter and word spacing

The letter-spacing and word-spacing properties allow you to set the spacing between letters and words in your text. You won’t use these very often, but might find a use for them to get a certain look, or to improve the legibility of a particularly dense font. They can take most length and size units.

So as an example, we could apply some word-spacing and letter-spacing like this:

word-spacing: 4px;
letter-spacing: 4px;

Proposed exercise: Spacing

Create a web page with at least 2 headers and 2 paragraphs, each one with different word and letter spacing (you may choose any values you like).

This text has 10 px word spacing:

Well I remember it as though it were a meal ago… Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator. Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did.

This text has 5 px letter spacing:

Well I remember it as though it were a meal ago… Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator. Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did.

Font shorthand

Many font properties can also be set through the shorthand property font. These are written in the following order:  font-stylefont-variantfont-weightfont-stretchfont-sizeline-height, and font-family. Among all those properties, only font-size and font-family are required when using the font shorthand property. A forward slash has to be put in between the font-size and line-height properties.

A full example would look like this:

font: italic normal bold normal 3em/1.5 Helvetica, Arial, sans-serif;

Proposed exercise: Font properties in one line

Create a new web page with at least five paragraphs and change the font properties using one single CSS line (font shorthand) for each one.

This is a big bold italic text with Special Elite font family.

This is a bigger bold italic text with Bonbon font family.

Other properties worth looking at

The above properties give you an idea of how to start styling text on a webpage, but there are many more properties you could use. We just wanted to cover the most important ones here. Once you’ve become used to using the above, you should also explore the following:

Font styles:

Text layout styles:

  • text-indent: Specify how much horizontal space should be left before the beginning of the first line of the text content.
  • text-overflow: Define how overflowed content that is not displayed is signaled to users.
  • white-space: Define how whitespace and associated line breaks inside the element are handled.
  • word-break: Specify whether to break lines within words.
  • direction: Define the text direction (This depends on the language and usually it’s better to let HTML handle that part as it is tied to the text content.)
  • hyphens: Switch on and off hyphenation for supported languages.
  • line-break: Relax or strengthen line breaking for Asian languages.
  • text-align-last: Define how the last line of a block or a line, right before a forced line break, is aligned.
  • text-orientation: Define the orientation of the text in a line.
  • overflow-wrap: Specify whether or not the browser may break lines within words in order to prevent overflow.
  • writing-mode: Define whether lines of text are laid out horizontally or vertically and the direction in which subsequent lines flow.

CSS. Unidad 1. Primeros pasos.

Introducción

En el módulo de Introducción al HTML, puedes encontrar los conceptos básicos para saber qué es HTML y cómo se usa para definir documentos que puedan se interpretados por un navegador web. Los títulos se verán más grandes que el texto y los párrafos empezarán en una línea nueva y habrá un espacio entre ellos. Los enlaces aparecerán en un color diferente y subrayados para distinguirlos del resto del texto. Estos estilos vienen predeterminados por el navegador y, en la práctica, son estilos muy básicos que el navegador aplica al fichero HTML para asegurarse, básicamente, de que sean legibles incluso si el autor de la página no especifica un estilo explícito. Sin embargo, Internet sería un lugar muy aburrido si todas las páginas web se vieran así, con los mismos estilos por defecto. Usando CSS se pueden controlar con precisión cómo se ven los elementos HTML en el navegador, pudiendo establecer el diseño que cada uno desee.

¿Para qué sirve CSS?

Como hemos mencionado, el CSS es un lenguaje informático que especifica cómo se presentan los documentos a los usuarios: cómo se diseñan, compaginan, etc.

Un documento suele ser un archivo de texto estructurado con un lenguaje de marcado: HTML es el más común, pero también existen otros como SVG o XML.

Presentar un documento a un usuario significa convertirlo en un formulario que el público pueda utilizar. Los navegadores, como por ejemplo FirefoxChrome o Edge, están diseñados para presentar documentos visualmente en una pantalla de ordenador, un proyector o una impresora.

El código CSS se puede usar para estilos de texto muy básicos como, por ejemplo, cambiar el color y el tamaño de los encabezados y los enlaces. Se puede utilizar también para crear un diseño, como podría ser convertir una columna de texto en una composición con un área de contenido principal y una barra lateral para información relacionada. Incluso se puede usar para crear efectos de animación.

Sintaxis de CSS

CSS es un lenguaje basado en reglas: cada usuario define las reglas que especifican los grupos de estilos que van a aplicarse a elementos particulares o grupos de elementos de la página web. Por ejemplo: «Quiero que el encabezado principal de mi página se muestre con letras grandes de color rojo».

El código siguiente muestra una regla CSS muy simple que proporcionaría el estilo descrito en el párrafo anterior:

h1 {
    color: blue;
    font-size: 5em;
}

La regla se abre con un selector. Este selecciona el elemento HTML al que queremos aplicar nuestros estilos. En este caso, cambiaremos el diseño de los encabezados de nivel uno (<h1>).

Luego tenemos un conjunto de llaves { }. Entre estas habrá una o más declaraciones, que tomarán la forma de pares de propiedad y valor. Cada par especifica cada una de las propiedades de los elementos seleccionados y el valor que queremos dar a esa propiedad.

Antes de los dos puntos, tenemos la propiedad; y después, el valor. Las propiedades CSS admiten diferentes valores, dependiendo de qué propiedad se esté especificando. En el ejemplo anterior, tenemos la propiedad color, que puede tomar varios valores de color. También tenemos la propiedad de font-size, que puede tomar varias unidades de tamaño como valor.

Una hoja de estilo CSS contendrá muchas de estas reglas, escritas una tras otra:

h1 {
    color: blue;
    font-size: 5em;
}

p {
    color: green;
}

Algunos valores se aprenden rápidamente, mientras que otros son difíciles de recordar. Las páginas de propiedades individuales que hay en el proyecto MDN proporcionan una forma rápida de buscar propiedades y sus valores en caso de olvidarlos o si deseas saber qué más se puede usar como valor. Puedes encontrar enlaces a todas las páginas de las propiedades CSS (junto con otras características) enumeradas en la referencia CSS del proyecto MDN. También puedes buscar «mdn css-feature-name» en tu motor de búsqueda favorito siempre que necesites obtener más información sobre alguna particularidad de CSS. Por ejemplo, intenta buscar «mdn color» y «mdn font-size».

Añadir CSS a un documento

Lo primero que debemos hacer es decirle al documento HTML que hay algunas reglas CSS que queremos que use. Hay tres formas diferentes de aplicar CSS a un documento HTML, sin embargo, por ahora, veremos la forma más habitual y útil de hacerlo: vincular el código CSS desde el encabezado del documento. Para ello bastará con crear un archivo en la misma carpeta que el documento HTML y guardarlo como estilos.css. La extensión .css indicará que nuestro archivo contiene código CSS.

Para vincular estilos.css a index.html, bastará con añadir la siguiente línea en algún lugar dentro del <head> del documento HTML:

<link rel="stylesheet" href="estilos.css">

Este elemento <link> utiliza el atributo rel para indicarle al navegador que debe utilizar una hoja de estilo y especifica la ubicación de esa hoja de estilo con el valor del atributo href. Puedes probar si el código CSS funciona correctamente añadiendo una regla al fichero estilos.css. Para ello puedes usar cualquier editor de código para añadir lo siguiente al archivo CSS:

h1 {
  color: blue;
}

Debes tener en cuenta que después de hacer cualquier cambio, deberás guardar los archivos HTML y CSS antes de volver a cargar la página en un navegador web. Ahora el título de nivel uno de la parte superior del documento debería ser azul. Si esto es correcto, ¡felicidades!: has aplicado correctamente un poco de CSS a un documento HTML. Si no cambia el color del encabezado, verifica que hayas escrito todo correctamente.

Puedes continuar trabajando en estilos.css localmente o usar cualquier otro editor (como repl.it) para continuar con este tutorial.

Ejercicio propuesto: Enlazar ficheros y añadir estilos

Nuestro punto de partida en esta unidad es un documento HTML. Copia el código que tienes a continuación y guárdalo en un nuevo archivo HTML para trabajar en tu propio ordenador. Después de eso, crea un nuevo archivo CSS para configurar todos los títulos <h1> en color rojo y guárdalo con el nombre «estilos.css» en la misma carpeta que el documento HTML. Finalmente verifica los resultados usando un navegador y no olvides validar el código.

Recuerda que la parte más importante de este ejercicio es vincular tu archivo CSS colocando una sola línea dentro de la sección <head>. Después de eso, dentro de «estilos.css» solo necesitarás insertar tres líneas:
  1. HTML file:
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Empezando con CSS</title>

    <!-- Utilizaremos los estilos que tengamos dentro de 'estilos.css' -->
    <link rel="stylesheet" href="estilos.css">
</head>
<body>   
    <h1>Yo soy un estilo de nivel 1</h1>

    <p>Esto es un párrafo de texto.</p> 
    <p>Esto es un párrafo y también un enlace a <a href="https://google.com">Google</a>.</p>

    <ul>
        <li>Primer elemento de una lista</li>
        <li>Segundo elemento de una lista</li>
        <li>Tercer elemento de una lista</li>
    </ul>
</body>
</html>
  1. Fichero CSS (estilos.css):
h1 {
  ...
}

Ejercicio propuesto: Estilos de encabezados

Usando los archivos HTML y CSS del ejercicio anterior, añade algunos encabezados <h2> y cambia el color con el que aparecen utilizando CSS. Puedes probar varios colores y elegir el que más te guste (red, green, blue, gray, purple, olive, navy, etc). Como de costumbre, verifica los resultados con tu navegador y no olvides validar el código.

Puede encontrar las palabras clave que identifican diversos colores aquí: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value.

Dar formato a elementos HTML

Al poner nuestro título de encabezado en rojo, ya hemos demostrado que podemos elegir un elemento HTML y darle formato. Hacemos esto con un selector de elementos: un selector que coincide directamente con el nombre de un elemento HTML. Para seleccionar todos los párrafos del documento, se usa el selector p. De esta forma, para hacer que el texto de todos los párrafos se muestren de color verde, bastará con utilizar el siguiente código:

p {
  color: green;
}

Puedes utilizar múltiples selectores a la vez, separándolos con una coma. Por ejemplo, si queremos que el texto de todos los párrafos y de todos los elementos de cualquier lista sea verde, el código a utilizar sería el siguiente:

p, li {
    color: green;
}

Ejercicio propuesto: Cambiar el color de varios elementos

Usando los archivos HTML y CSS del ejercicio anterior, cambia el color de los párrafos y elementos de la lista. Puedes probar varios colores y elegir el que más te guste (red, green, blue, gray, purple, olive, navy, etc). Como de costumbre, verifica los resultados con tu navegador y no olvides validar el código.

Puede encontrar las palabras clave que identifican diversos colores aquí: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value.

Aplicar formato según el estado

CSS nos ofrece la capacidad de aplicar formato a los elementos en función de su estado. Un ejemplo sencillo es el estilo de los enlaces. Cuando damos formato a un enlace, necesitamos seleccionar el elemento <a> (anchor). Tiene diferentes estados dependiendo de si se ha visitado o no, si se pasa el ratón por encima, o si se presiona con el teclado o se hace clic (se activa). Puedes usar CSS para dar formato a estos diferentes estados. Utilizando el código CSS que se muestra a continuación se deberían visualizar en color rosa los enlaces que no se han visitado y en verde los que sí.

a:link {
  color: pink;
}

a:visited {
  color: green;
}

También puedes cambiar la apariencia del enlace, por ejemplo, eliminando el subrayado, lo que se logra mediante la siguiente regla:

a:hover {
  text-decoration: none;
}

En el ejemplo de arriba hemos eliminado el subrayado del enlace cuando el ratón se pasa por encima, y se puede eliminar de todos los estados de un enlace. Sin embargo, es conveniente recordar que en una página web real deberás asegurarte de que los visitantes sepan reconocer que se trata de un enlace. Que aparezca subrayado puede ser una pista importante para que las personas se den cuenta de que pueden hacer clic en una palabra dentro del párrafo, ya que es a lo que están acostumbrados. Al igual que con todo en CSS, existe la posibilidad de que tus cambios resten accesibilidad al documento.

Ejercicio propuesto: Aplicar estilos a los enlaces

Usando los archivos HTML y CSS del ejercicio anterior, inserta varios párrafos con algunos otros enlaces a tus páginas preferidas y cambia el color de todos los enlaces. También debes usar diferentes colores cuando se ha visitado el enlace y cuando el ratón está sobre el enlace. Puedes probar varios colores y elegir el que más te guste (red, green, blue, gray, purple, olive, navy, etc). Como viene siendo habitual, verifica los resultados con tu navegador y no olvides validar el código.

Puedes encontrar las palabras clave que identifican diversos colores aquí: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value.

Cambiar el comportamiento predeterminado de los elementos

Cuando visualizamos una página web, incluso con un código tan simple como el de nuestro ejemplo, podemos ver que el navegador facilita la legibilidad de este documento HTML al añadir un estilo predeterminado. Los títulos se muestran grandes y en negrita, y la lista tiene viñetas. Esto sucede porque los navegadores tienen hojas de estilo internas que contienen estilos predeterminados, los cuales se aplican a todas las páginas por defecto. Sin ellos, todo el texto se amontonaría y tendríamos que darle formato desde cero. Todos los navegadores modernos suelen mostrar el contenido HTML por defecto de la misma manera.

Sin embargo, a menudo querrás algo diferente a la elección que ha hecho el navegador. Esto se puede solucionar con el simple hecho de escoger el elemento HTML que deseas cambiar y utilizar una regla CSS para cambiar su apariencia.  Un buen ejemplo es <ul>, que muestra una lista desordenada. Por defecto tiene viñetas, pero si decidimos que no las queremos, podemos eliminarlas fácilmente de este modo:

ul {
  list-style-type: none;
}

Puedes consultar en MDN la propiedad list-style-type para ver qué valores admite. Echa un vistazo a la página de list-style-type y encontrarás un ejemplo interactivo en la parte superior donde podrás probar diferentes valores (todos los permitidos se detallan más abajo en esa misma página). También descubrirás en esa página que además de eliminar las viñetas de la lista, también puedes cambiarlas.

Ejercicio propuesto: Cambiar las viñetas de una lista

Utilizando los archivos HTML y CSS del ejercicio anterior, intenta configurar el list-style-type con square. Como de costumbre, verifica los resultados con tu navegador y no olvides validar el código.

Deberías obtener un resultado similar a este:
  • Primer elemento de una lista
  • Segundo elemento de una lista
  • Tercer elemento de una lista

Ejercicio propuesto: Cambiar el estilo de una lista numerada

Usando los archivos HTML y CSS del ejercicio anterior, agregue una lista ordenada (<ol>) y configura el list-style-type con upper-roman. Como de costumbre, verifica los resultados con tu navegador y no olvides validar el código.

Deberías obtener un resultado similar a este:
  • Elemento uno
  • Elemento dos
  • Elemento tres
  1. Elemento uno
  2. Elemento dos
  3. Elemento tres

Utilizando clases

Hasta ahora, hemos utilizado selectores cuyo nombre se basa en el nombre de elemento que reciben en HTML. Esto funciona siempre que se desee que todos los elementos de ese tipo tengan el mismo aspecto en el documento. La mayoría de las veces no es el caso, por lo que deberás encontrar una manera de seleccionar un subconjunto de los elementos sin que cambien los demás. La forma más común de hacer esto es añadir una clase al elemento HTML y establecer el estilo que se aplicará al utilizar dicha clase.

Puedes añadir un atributo de clase a cualquier elemento dentro de tu fichero HTML. Por ejemplo, podríamos utilizar el atributo «class» sobre elementos de tipo lista de la siguiente forma:

<ul class="lista-roja-con-cuadrados">
  <li>Elemento uno</li>
  <li>Elemento dos</li>
  <li>Elemento tres</li>
</ul>
<ul class="lista-azul-con-circulos">
  <li>Elemento uno</li>
  <li>Elemento dos</li>
  <li>Elemento tres</li>
</ul>

Después de escribir ese código HTML, en tu CSS, puedes diseñar las clases lista-roja-con-cuadrados y lista-roja-con-cuadrados creando un par de selectores que comiencen con un punto:

.lista-roja-con-cuadrados {
  list-style-type: square;
  color: red;
}
.lista-azul-con-circulos {
  list-style-type: circle;
  color: blue;
}

Para observar el resultado después de escribir nuevo código HTML y CSS, bastará con guardar los archivos y refrescar el contenido del navegador pulsando Ctrl+F5.

Ejercicio propuesto: Estilos diferentes para cada lista

Usando los archivos HTML y CSS del ejercicio anterior, añade varias listas para obtener algo similar al resultado que se muestra a continuación. Como de costumbre, verifica los resultados con tu navegador y no olvides validar el código.

En lo que respecta a las listas no ordenadas (<ul>) debes crear 4 clases diferentes, cada una de ellas con un valor diferente de la propiedad list-style-type (none, disc, circle, square). Para las listas ordenadas (<ol>) debes crear otras clases, cada una también con valores diferentes para la propiedad list-style-type (upper-roman, lower-greek, lower-alpha, upper-alpha).

Listas no ordenadas

  • Elemento uno
  • Elemento dos
  • Elemento tres
  • Elemento uno
  • Elemento dos
  • Elemento tres
  • Elemento uno
  • Elemento dos
  • Elemento tres
  • Elemento uno
  • Elemento dos
  • Elemento tres

Listas ordenadas

  1. Elemento uno
  2. Elemento dos
  3. Elemento tres
  1. Elemento uno
  2. Elemento dos
  3. Elemento tres
  1. Elemento uno
  2. Elemento dos
  3. Elemento tres
  1. Elemento uno
  2. Elemento dos
  3. Elemento tres

Ejercicio propuesto: Usar CSS con encabezados, párrafos y texto general

Cambia el color de diversos elementos de ejercicios previos de HTML en los que utilizaste encabezados, párrafos y texto formateado en las unidades 1 y 2 (https://fernandoruizrico.com/html-unidad-1/ and https://fernandoruizrico.com/html-unidad-2/). No olvides validar tu código de nuevo.

Recuerda que puedes encontrar las palabras clave que identifican diversos colores aquí: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value.

Ejercicio propuesto: Usar CSS con hipervínculos

Cambia el color de diversos elementos de la unidad 3 de HTML (https://fernandoruizrico.com/html-unidad-3/). No olvides validar tu código de nuevo.

Recuerda que puedes encontrar las palabras clave que identifican diversos colores aquí: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value.

Ejercicio propuesto: Usar CSS con listas

Cambia el color, las viñetas y la numeración de diversas listas de los ejercicios de listas de la unidad 4 de HTML (https://fernandoruizrico.com/html-unidad-4/). No olvides validar tu código de nuevo.

Recuerda que puedes encontrar las palabras clave que identifican diversos colores aquí: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value.

HTML. Unidad 5. Imágenes.

Introducción

Al principio, las páginas web solo contenían texto y resultaba más bien aburrida. Afortunadamente, no pasó mucho tiempo antes de que se añadiera la capacidad de insertar imágenes (y otros tipos de contenido más interesantes). Existen elementos multimedia que debemos tener en cuenta, pero es lógico comenzar con el humilde elemento <img> utilizado para insertar una imagen simple en una página web. En esta unidad veremos en detalle cómo usar este elemento, incluidos sus conceptos básicos y cómo añadir pies de imagen usando <figure>.

¿Cómo ponemos una imagen en una página web?

Para poner una imagen simple en una página web, utilizamos el elemento <img>. Se trata de un elemento vacío (lo que significa que no contiene texto o etiqueta de cierre) que requiere por lo menos de un atributo para ser utilizado: src (a veces denominado por su nombre completo, source). El atributo src contiene una ruta que apunta a la imagen que quieres poner en la página, que puede ser una URL relativa o absoluta, de la misma forma que el elemento <a> contiene los valores del atributo href.

Por ejemplo, si tu imagen se llama dinosaurio.jpg, y está en el mismo directorio que tu página HTML, incluir la imagen de la siguiente manera:

<img src="dinosaurio.jpg" />

El código anterior debería darnos el resultado siguiente:

Si la imagen está en el subdirectorio imagenes, ubicado en el mismo directorio que la página HTML (lo que Google recomienda con fines de indexación y posicionamiento en buscadores SEO), entonces la imagen se puede incluir así:

<img src="imagenes/dinosaurio.jpg" />

Los motores de búsqueda también leen los nombres de archivo de imagen y esto cuenta para el SEO.  Por lo tanto, elige para tu imagen un nombre descriptivo. Por ejemplo, dinosaurio.jpg es mejor que img835.png.

También puedes incluir la imagen usando la URL absoluta, por ejemplo:

<img src="https://www.ejemplo.com/imagenes/dinosaurio.jpg" />
...
<img src="https://developer.mozilla.org/static/img/favicon144.png" />

Aunque esta última opción es menos habitual, ya que provoca que el navegador tenga que buscar la dirección IP desde el servidor DNS cada vez. Al ser posible, conviene almacenar las imágenes de tu página web en el mismo servidor donde guardes tu código HTML.

Por último, conviene mencionar que la mayoría de imágenes tienen derechos de autor. Por ello, no debes mostrar una imagen en tu página web a menos que:

  1. seas dueño de la imagen,
  2. tengas permiso escrito explícito del dueño de la imagen o 
  3. tengas suficientes pruebas de que la imagen es de dominio público.

El incumplimiento de las normas de los derechos de autor es un acto ilegal y poco ético. Por lo tanto, no debes apuntar nunca tu atributo src a una imagen que esté alojada en un sitio web si no tienes el permiso para hacerlo. Esto se llama hotlinking. Asimismo es ilegal robar el ancho de banda de alguien.  Además, ralentiza tu página y te deja sin control sobre la imagen si la eliminan o reemplazan por otra que incluso podría resultar embarazosa.

Texto alternativo

El próximo atributo que veremos es  alt. Su valor debe ser una descripción textual de la imagen para usarla en situaciones en que la imagen no se pueda mostrar o tarde demasiado en mostrarse por una conexión de Internet muy lenta. Por ejemplo, nuestro código anterior podría modificarse así:

<img src="imagenes/dinosaurio.jpg"
     alt="La cabeza y el torso de un esqueleto de dinosaurio;
           tiene una cabeza grande con dientes largos y afilados">
...
<img src="https://developer.mozilla.org/static/img/favicon144.png"
     alt="MDN logo" />

La forma más fácil de probar el texto alt es escribir mal el nombre de archivo. Si, por ejemplo, escribimos el nombre de archivo de nuestra imagen como dinosaurioooooo.jpg, el navegador no podrá mostrar la imagen, y en su lugar mostrará el texto alternativo.

Además de ser necesario (la validación de tu página web no será correcta si omites algún texto alternativo), el texto alternativo podría resultar necesario por varias razones:

  • El usuario tiene alguna discapacidad visual y utiliza un lector de pantalla para leer el contenido de la web. De hecho, disponer de texto alternativo para describir las imágenes es útil para la mayoría de los usuarios.
  • Como ya hemos dicho anteriormente, es posible que se haya escrito mal el nombre del archivo o su ruta.
  • El navegador no admite el tipo de imagen. Algunas personas aún usan navegadores de solo texto, como Lynx, que muestran el texto del atributo alt.
  • Quieres que los motores de búsqueda puedan utilizar este texto. Por ejemplo, los motores de búsqueda pueden hacer coincidir el texto alternativo con la consulta de búsqueda.
  • Los usuarios han desactivado las imágenes para reducir el volumen de transferencia de datos y de distracciones. Esto puede suceder especialmente en teléfonos móviles y en países en los que el ancho de banda está bastante limitado.

Para saber qué hay que escribir exactamente en el atributo alt, debemos pensar primero por qué la imagen está en ese lugar. En otras palabras, qué se pierde si la imagen no aparece:

  • Decoración. Para las imágenes decorativas deberían utilizarse imágenes de fondo CSS. Pero si es inevitable usar HTML, la mejor forma de hacerlo es con alt="". Si la imagen no es parte del contenido, el lector de pantalla no debería malgastar el tiempo en leerla.
  • Contenido. Si tu imagen proporciona información significativa, se debe proporcionar la misma información en un texto alternativo (alt) breve. O mejor aún, en el texto principal que todos pueden ver. No escribas texto alternativo redundante. ¿Acaso no resultaría molesto para un usuario con visión ordinaria si todos los párrafos se escribieran dos veces en el contenido principal? Si la imagen se describe en el cuerpo principal del texto de modo adecuado, puedes simplemente usar alt="".
  • Enlace. Al poner una imagen dentro de una etiqueta <a> para convertirla en un enlace, aun debes proporcionar texto de enlace accesible. En tal caso podrías escribirlo dentro del mismo elemento <a>, o dentro del atributo alt de la imagen. Lo que mejor funcione en tu caso.
  • Texto. No deberías poner tu texto en imágenes.  Si tu título de encabezado principal necesita, por ejemplo, un sombreado paralelo, usa CSS para ello en vez de poner el texto en una imagen. Pero, si realmente no puedes evitarlo, deberías proporcionar el texto en el atributo alt.

Resumiendo, el objetivo es ofrecer una experiencia de navegación adecuada en términos de usabilidad, incluso cuando las imágenes no puedan verse. Esto asegura que ningún usuario se pierda ninguna parte del contenido.

Puedes consultar la guía de texto alternativo de Mozilla para obtener más información.

Anchura y altura

Puedes usar los atributos  ancho (width) y alto (height) para especificar la anchura y altura de cada imagen. Puedes encontrar el ancho y el alto de cualquier imagen de diversas maneras. Por ejemplo, con el botón derecho del ratón, o en Mac también puedes usar  Cmd + I  para mostrar información del archivo de imagen. Volviendo a nuestro ejemplo, podríamos hacer esto:

<img src="imagenes/dinosaurio.jpg"
     alt="La cabeza y el torso de un esqueleto de dinosaurio;
          tiene una cabeza grande con dientes largos y afilados"
     width="400"
     height="341">

Sin embargo, no deberías alterar el tamaño de tus imágenes utilizando atributos HTML. Las imágenes podrían verse pixeladas o borrosas si estableces un tamaño demasiado grande; o bien demasiado pequeñas, y se desperdiciaría ancho de banda descargando una imagen que no se ajusta a las necesidades del usuario. La imagen también podría quedar distorsionada, si no mantienes la proporción de aspecto correcta. Deberías utilizar un editor de imágenes para dar a tu imagen el tamaño adecuado antes de colocarla en tu página web. Y si tienes que alterar el tamaño de una imagen desde tu código fuente, es mejor usar CSS.

Título de la imagen

Al igual que con los enlaces, también puedes añadir atributos title a las imágenes para proporcionar más información de ayuda si es necesario. En nuestro ejemplo, podríamos hacer esto:

<img src="imagenes/dinosaurio.jpg"
     alt="La cabeza y el torso de un esqueleto de dinosaurio;
          tiene una cabeza grande con dientes largos y afilados"
     width="400"
     height="341"
     title="Exposición de un T-Rex en el museo de la Universidad de Manchester.">

Esto nos da una etiqueta de ayuda (tooltip) como las de los enlaces. Sin embargo, no se recomienda incluir esta propiedad en las imágenes, ya que title presenta algunos problemas de accesibilidad, principalmente porque los lectores de pantalla (screen readers) tienen un comportamiento imprevisible y la mayoría de navegadores no la mostrarán a menos que pases el ratón por encima de la imagen (y por tanto es inútil para quien usa teclado). Si estás interesado en este tema, puedes leer el artículo The Trials and Tribulations of the Title Attribute de Scott O’Hara.

Resumiendo, es más adecuado incluir en el texto principal de la página la información que pondríamos en el title, en lugar de adjuntarla en la imagen.

Ejercicio propuesto: Insertar imágenes

Crea una página web para mostrar varias imágenes. Tienes que usar la etiqueta básica <img> y el atributo «src» para apuntar a la URL de cada imagen individual. Por ejemplo, puedes usar imágenes como estas:

https://developer.mozilla.org/static/img/favicon144.png

https://raw.githubusercontent.com/mdn/learning-area/master/html/multimedia-and-embedding/images-in-html/dinosaur_small.jpg

https://validator.w3.org/images/w3c.png

También debes añadir un texto alternativo a cada imagen y verificar que se muestra al escribir mal la URL de cada imagen. Finalmente experimente con diferentes valores de ancho y alto para ver cuál es su efecto.

Imágenes con enlaces

Este ejemplo se basa en los anteriores y muestra cómo convertir la imagen en un enlace. Para hacerlo, debes anidar la etiqueta <img> dentro de <a>. Además, se debe usar el texto alternativo para describir el recurso al que apunta el enlace, como si se estuviera usando un enlace de texto en su lugar:

<a href="https://developer.mozilla.org">
  <img src="https://developer.mozilla.org/static/img/favicon144.png"
       alt="Visita la web de MDN" />
</a>

Ejercicio propuesto: Las diez páginas más importantes

Crea una página web que muestre una lista ordenada (<ol>) de las diez páginas web que más te gusten. Debes utilizar imágenes para crear enlaces a cada página y establecer el atributo de altura con el mismo valor para todas las imágenes para que todas tengan la misma altura. Por ejemplo:

<ol>
  <li>
    <a href="https://developer.mozilla.org">
      <img src="https://developer.mozilla.org/static/img/favicon144.png" 
           alt="MDN site" height="100" />
    </a>
  </li>
  <li>
    <a href="https://validator.w3.org/">
      <img src="https://validator.w3.org/images/w3c.png" 
           alt="Markup Validation Service" height="100" />
    </a>
  </li>
  ...
</ol>

Comentar imágenes con figure y figcaption

Hay varias formas en que puedes añadir un pie a tu imagen. Por ejemplo, nada te impediría hacer esto:

<div class="figure">
  <img src="imagenes/dinosaurio.jpg"
       alt="La cabeza y el torso de un esqueleto de dinosaurio;
            tiene una cabeza grande con dientes largos y afilados"
       width="400"
       height="341">

  <p>Exposición de un T-Rex en el museo de la Universidad de Manchester.</p>
</div>

Este código es completamente correcto, ya que incluye el contenido que se necesita y es muy personalizable con CSS. Pero hay un problema: no hay nada que vincule semánticamente la imagen con su título, lo que puede causar problemas a los lectores de pantalla. Por ejemplo, cuando hay 50 imágenes y leyendas, ¿qué leyenda se corresponde con cada imagen?

Una solución mejor es utilizar los elementos HTML5 <figure> y <figcaption>. Estos se crearon exactamente para este propósito: proporcionar un contenedor semántico para las figuras y vincular claramente la figura con el pie. Nuestro ejemplo anterior podría reescribirse así:

<figure>
  <img src="imagenes/dinosaurio.jpg"
       alt="La cabeza y el torso de un esqueleto de dinosaurio;
            tiene una cabeza grande con dientes largos y afilados" width="400"
       height="341">

  <figcaption>Exposición de un T-Rex en el museo de la Universidad de Manchester.</figcaption>
</figure>

El elemento <figcaption> le dice al navegador, o a alguna tecnología de apoyo, que el texto que contiene describe la imagen que está contenida en el elemento <figure>. Desde el punto de vista de la accesibilidad, los pies de imagen y el texto alternativo alt cumplen funciones diferentes. Los pies de imagen benefician incluso a quien puede ver la imagen, mientras que el texto alt proporciona la misma función en una imagen ausente. Por tanto, los subtítulos y el texto alt no deberían decir lo mismo, porque ambos aparecen si la imagen no se muestra.

También debemos tener en cuenta que el elemento figure no ha de contener una imagen necesariamente. Es una unidad de contenido independiente que:

  • Expresa un significado en una forma compacta y fácil de entender.
  • Se puede poner en varios sitios en el flujo lineal de la página.
  • Proporciona información esencial que da apoyo al texto principal.

Un elemento figure podría contener varias imágenes, un trozo de código, audio, video, ecuaciones, una tabla, o cualquier otra cosa.

Ejercicio propuesto: Figuras con leyenda

Crea una página web para mostrar varias imágenes que te gusten, usando el elemento <figure>, y agrega un título a cada una usando el elemento <figcaption>, como se hace en el siguiente ejemplo:

<figure>
  <img src="https://developer.mozilla.org/static/img/favicon144.png"
       alt="Página web de MDN (Mozilla Developer Network)">
  <figcaption>MDN Logo</figcaption>
</figure>

<figure>
  <img src="https://validator.w3.org/images/w3c.png"
       alt="Validador de W3C">
  <figcaption>W3C Logo</figcaption>
</figure>

...

Ejercicio propuesto: Las diez películas más interesantes

Crea una nueva página web que muestre una lista ordenada (<ol>) de las diez películas que más te gusten. En este caso, debe utilizar figuras con subtítulos para crear enlaces a cada página. Utiliza el mismo valor para el atributo de altura de todas las imágenes para que todas tengan la misma altura. Por ejemplo:

<ol>
  <li>
    <a href="https://en.wikipedia.org/wiki/Steve_Jobs_(film)">
      <figure>
        <img src="https://upload.wikimedia.org/wikipedia/commons/4/49/SteveJobsMacbookAir.JPG" 
             alt="Steve Jobs y el Macbook Air" height="100" />
        <figcaption>Steve jobs</figcaption>
      </figure>
    </a>
  </li>
  <li>
    <a href="https://en.wikipedia.org/wiki/2001:_A_Space_Odyssey_(film)">
      <figure>
        <img src="https://upload.wikimedia.org/wikipedia/en/0/09/2001child2.JPG" 
             alt="Bebé, espacio, y la Tierra" height="100" />
        <figcaption>2001: Una Odisea Espacial</figcaption>
      </figure>
    </a>
  </li>
  ...
</ol>

Test

Comprueba tus conocimientos con este test sobre imágenes y otros conceptos relacionados con esta unidad.