SITERAW

Text formatting

Ready to start designing your website like a true web developer? Look no further, this chapter is for you.

In the last chapter we learned the basics of the CSS language: what it is, why it's used, where to write CSS code and how to apply a CSS style to a specific HTML element.

Text formatting simply means that we're going to modify the appearance of text content.

About that... I don't want to complain but we only ever learned how to change the color of our text. Is that all there is to CSS?

It's true that we have only seen one CSS property until now.

But that was just for demonstration purposes so you could see the changes in real time on your web page.

From now on, we'll be using many more CSS properties to format our text.

In this chapter we'll learn how to adjust the text size, modify the font, apply a text effect such as italics, align the paragraphs.

At the end of this chapter your website will (finally) start to look like something.

Text size

To change the size of your text, all you need is one CSS property: font-size.

But what do we enter for its value?

There are two methods for stipulating text size in CSS:

  • an absolute value specifies a font size in pixels, inches, points, millimeters and so on.
  • a relative value specifies a font size as a percentage of the default text size of the page.

Both methods are used significantly for web designing.

An absolute size

To define an absolute size in CSS we use what is called length values.

These can be points, pixels, inches, centimeters, millimeters or even pica.

For web development, the preferred format is almost always the pixel.

Other length values such as inches are less suited for screen display.

Here is how you use pixels with the font-size property.

p { font-size: 16px; }

The length unit here is the pixel so we append its symbol px to the value we want.

The text in your paragraphs should now be 16 pixels high... which should not change anything as 16 pixels is the default font size on most browsers.

Try using a larger or smaller size to see the text change on your web page.

As I've mentioned, px is the symbol for the pixel unit. There are other absolute units such as the inch in, the centimeter cm or the point pt. Pixel lengths are generally preferred for web usage.

A relative size

Relative font sizes are, as their name suggests, relative.

Ok. That's great. But what does it means? I thought we already had pixels, inches and everything else?

Pixels and other units are absolute values.

That means 1 pixel will always measure 1 pixel.

Relative values on the other hand use a different set of units that are flexible, adaptable and most importantly context depended. The context usually being the browser's default settings, or those of your web page if you've decided to overwrite them.

One way of specifying a relative value is by downright entering their sizes.

Here is a list of the different values you can set and their meaning.

  • xx-small : extremely small
  • x-small : very small
  • small : small
  • medium : medium
  • large : large
  • x-large : very large
  • xx-large : maternal filiation comedy

You can use these values in your CSS code as follows.

h1 { font-size: large; }

p { font-size: small; }

While this method works, there is an obvious drawback: there are only seven sizes available.

Fortunately you can also use other units to define a relative font size.

One of those is the em unit.

In CSS, one em is equal to the font size of the parent element.

  • If you want a regular text size, stick with 1.
  • I you want a larger text size, enter a value greater than 1 such as 1.5em.
  • I you want a smaller text size, enter a value lower than 1 such as 0.8em.

Decimals are of course preferred as 2em would double the size of the text.

Here is how you use this unit in CSS.

h1 { font-size: 1.5em; }

p { font-size: 0.8em; }

There are other units available.

You can use em, rem, ex or percentages %.

Besides rem which is a variation of em, they all have different bases.

But how much is 1em in pixels? How do I convert from relative values to absolute values and vice versa?

You don't.

That's the point of relative values: their absolute values are conditioned on either the format of a parent element or the settings of the browser.

By default, 1em is worth 16px for most desktop browser.

But that value may be lower on certain smartphones and tablets.

Additionally, the em unit is dependent on the size of parent or ancestor elements.

For example take this HTML code.

<div>
	<p>Welcome to <span>SiteRaw</span></p>
</div>

As we said, the default value of 1em on most browsers is 16px.

But if the parent element has a larger font size it will affect the base value of the em unit.

div { font-size: 20px; }

p { font-size: 1em; }

span { font-size: 1.5em; }

Within the <div> element the value of 1em is not longer 16px but 20px.

And any text within a <span> tag will have a font size of 30px.

If you want the relative values of em without them being affected by parent or ancestor elements, you can use the rem unit. It's identical to em but it ignores parent tags and only depends on the font size of the root element, the <html> tag.

Font family

In CSS, the font family is the typeface that will be applied to your text.

Usually they are simply called "fonts" but the names aren't necessarily interchangeable.

Regardless of semantics and terminology, applying a font (or a typeface) to a portion of text on your web page is very easy.

The only issue that comes up is the availability of the font.

For a font to be displayed correctly we need the user to have that font installed.

Otherwise, if a user doesn't have the font you want to render on your page, the browser will apply a default typeface that may have little visual similarities with what you were expecting.

Granted, everyone has "Arial" installed...

But what about the newest "SEWER2154.otf" font that you were planning to use on your edgy extreme metal website?

The good news is that since CSS3 you can embed a font directly from your style sheet. I'll explain how to do so in a moment.

Modifying the font

As I said, changing the font is easy.

The CSS property that allows you to specify a typeface is font-family.

Here is how it's used.

font-family: font;

Just replace the value font with whatever typeface identifier or font family names you want to use.

We'll see which fonts are most appropriate for web usage in just a second.

The font-family property also allows you to indicate several font names, separated by commas.

font-family: font1, font2, font3, font4;

Every font name after the first one is an alternative font.

The reason for supplying a prioritized list rather than a single font is that the other fonts will act as a back-up in case the user doesn't have the first font installed.

In our example, the browser will first check to see if the user has font1 installed.

If he has, everything goes well and it is displayed.

If he doesn't, the browser proceeds to check with font2 and so on all the way to font4.

The last font is a fallback font or last resort font that everyone is sure to have. It's usually serif or sans-serif.

Ok, but what fonts can I use on the web? You still haven't given us a list of font names!

Technically you can use any font you want.

If a font exists, it can be displayed on the web.

The problem is with operating system and browser compatibility.

Luckily, there are a few generic fonts also called web safe fonts that are deemed reasonably likely to be present on most if not all computers.

Web safe fonts

Web safe fonts are the fonts that ensure maximum compatibility with most browsers and operating systems.

Here is a list of the most common web safe fonts:

  • Arial
  • Arial Black
  • Comic Sans MS
  • Courier New
  • Georgia
  • Helvetica
  • Impact
  • Palatino
  • Times New Roman
  • Trebuchet MS
  • Verdana
List of web safe fonts
List of web safe fonts

Many web developers recommend specifying at least three or four fonts, starting with the font you want and ending with either serif or sans-serif.

I find it a bit excessive but it's really up to you and how many alternatives you want to offer.

You keep talking about serif and sans-serif, what are they?

In this context they are fonts.

They're the most basic ones you can find and they will always be rendered even if for whatever reason the user has no fonts installed on his computer.

But serif and sans serif have a wider meaning that predates web development.

In typography, serifs are semi-structural elements added for embellishment to the characters of a typeface.

As such all fonts can be divided based on whether their letters possess serifs or not. In the latter case they're called sans serif fonts.

Serif and sans serif
Serif and sans serif

Serif fonts are considered easier to read in printed as the letters are more distinctive.

Most books are usually published with a serif typeface.

Times New Roman and Georgia are serif fonts whereas Arial and Verdana are sans serif.

Serif and sans serif
Serif and sans serif

This distinction is somewhat important when indicating alternative fonts.

Your fallback fonts should if possible be of the same type as the preferred font.

For example, if I'm aiming for a sans serif font my CSS code would be the following.

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

All the possible fonts are sans-serif.

If the font name includes spaces I suggest you surround it with quotes as I've done with "Arial Black". It becomes necessary when the font name contains numbers or special characters.
In addition to serif and sans serif, there are other font types such as monospace, cursive and fantasy. They aren't used much and the difference in style is minimal compared to serif/sans serif.

Using a custom font

You now know how to change the typeface of your text and provide alternative fonts to the user.

These fonts suck. I want to use my own fonts instead of Arial and Verdana.

For a long time this wasn't possible.

You either had to use a web safe font or try and guess which fonts were installed on the user's computer and hope you were right.

Then CSS 3 came around and it's now possible to embed any font directly in your CSS style sheet.

I'll be the first one to admit that it's a pretty cool feature but there are still quite a few drawbacks to this practice.

These are some of the few inconveniences of this method.

  • Embedding a font means that the user will have to load it through his browser. Some fonts may weigh up to 1 MB or more and that means he'll reach puberty before he finishes loading your website.
  • Many fonts are subject to copyright, making them illegal for use on your website. There are still many free alternatives so this isn't much of a problem if you know the license of your font.
  • There are several font formats and not every format is compatible with every browser. This is less of a problem today as we'll see further on, but it can complicate things for those using outdated browsers.

The last two points aren't as big of a deal as they once were.

The biggest impediment to using custom fonts is the size of each file, so if you do use them make sure it's with parsimony.

But since we started talking about font formats, let's take a quick detour and introduce them properly.

The different font formats

Just as image files have different formats depending among other factors on their method of compression, font files also have distinct formats that affect the way their data is stored.

Here is a list of the main font formats used on the web.

  • .ttf : TrueType Font. Works with Internet Explorer 9 and onward and all other browsers.
  • .eot : Embedded OpenType. Works with Internet Explorer only, on all versions. This is a proprietary format produced by Microsoft.
  • .otf : OpenType Font. Similar to .ttf, works on all browsers except the older versions of Internet Explorer (prior to IE 9).
  • .svg : Scalable Vector Graphics. For a long time this was the only format supported on iPhone and iPad browsers. Works on most versions of Safari.
  • .woff : Web Open Font Format. A newer format designed specifically for the web. Works on all recent browsers.

Generally, you want to stick with .ttf, .otf and .woff.

Some web developers prefer to provide a font version in every format to ensure maximum compatibility.

Font formats and browser compatibility
Font formats and browser compatibility

Declaring a new font

To define a custom font you first need a font file in one of the aforementioned formats.

There are many websites on the Internet that propose free fonts to download. One font directory I can recommend is Font Squirrel, but there are many others you can try out.

Once you've downloaded your font files, extract them to the same directory as your CSS style sheet.

This is what you should have in your file explorer.

Fonts files next to the style sheet
Fonts files next to the style sheet

In this demonstration the two fonts files are Learning.otf and Rust.otf.

Using a custom font in CSS is a twofold process.

First you have to declare a new font and then apply it on the selector on you want.

We already know how do perform the second action so let's focus on the declaration first.

This is how you declare a new font in CSS.

@font-face {
    font-family: 'SiteRaw';
    src: url('SiteRaw.otf');
}

The syntax looks similar to that of a selector but it's actually something completely different.

Anything started with a commercial at @ in CSS is called a "rule" or "at-rule".

By convention, these go at the top of your CSS document before any style formatting.

This rule is named @font-face and contains two "properties".

I use quotes because while they look like CSS properties, they are in fact called descriptors and work in a slightly different fashion.

Here of the two descriptors we used.

  • font-family declares the name of the font. In our example it's SiteRaw but it can be anything you want. It's simply the identifier that we'll write when we want to apply the font.
  • src declares the source (location) of the font file. In our example it's SiteRaw.otf. But if I wanted to use one of the two fonts files from the image above, I would write either Rust.otf or Learning.otf.

This short code just "created" a new font with the name SiteRaw and whose file was located at SiteRaw.otf in the same directory as our CSS style sheet.

But what if I have several font formats for the same font?

Easy.

Just enter as many formats as you want.

The browser will automatically download the one it can read and ignore the rest.

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

Now that we know how to declare a new font, all that's left to learn is how to apply it to a specific HTML element.

This is perhaps the easiest part... all you need to do is use the font-family property.

But instead of using a generic font name you simply enter the name of the font you previously declared.

Just make sure the custom font name you used in the @font-face matches the one you use in your selector properties.

CSS font declaration
CSS font declaration

The following example will show you how to define and apply two custom fonts in CSS.

First the HTML code.

<h1>Welcome to SiteRaw</h1>

<p>SiteRaw is the best site on the web.</p>

Nothing special here.

Now let's move on to the CSS code.

@font-face {
    font-family: 'Rust';
    src: url('Rust.otf');
}
@font-face {
    font-family: 'Learning';
    src: url('Learning.otf');
}

h1 { font-family: 'Rust'; }
p { font-family: 'Learning'; }

We defined two custom fonts and applied them respectively to the <h1> and <p> elements.

Here is what you should see in your browser.

Custom fonts with CSS
Custom fonts with CSS

Results obviously depend on which fonts you have chosen.

Typographical decorations

CSS has many properties that allow you to stylize your text.

You can apply italics, bold, underline, overline and even make your text blink. Just don't actually use the last one, blinking text is a serious PTSD trigger for veteran web developers.

Why do I need CSS for that? I thought we already had the <em> tag for italic text!

Where did you learn that?

Certainly not from me.

In fact, during the Organize your text chapter I specifically stated that HTML highlight tags such as <strong>, <em> and <mark> were not to be used for text formatting.

HTML for content, CSS for style. Repeat that every day if you have to.

HTML tags such as <em> and <strong> are used to emphasize words. They communicate to the browsing agent that their content is to be treated as important text.

By default, most browsers will apply a certain text style depending on the tag (bold for <strong>, italics for <em> and so on).

But that is not the purpose of these elements.

Applying bold, italics, underlined and other text decorations belongs to the realm of CSS.

Let's learn how to do it.

Italics in CSS

With CSS you can apply italics to any HTML element you choose, be they paragraphs, titles or anything else.

To apply italics in CSS you use font-style.

This property can take three values:

  • italic : the text will be written in italics.
  • oblique : the text will be displayed obliquely.
  • normal : the text will be set back to normal (default).

Here is a demonstration.

p { font-style: italic; }

This code will make make your paragraphs italic.

But let's say you want to remove the italics from the <em> tag.

em { font-style: normal; }

With this, the <em> element will no longer be italicized.

What is the difference between italic and oblique text? They both look the same to me.

An oblique is a roman font that has been skewed a certain number of degrees, usually between eight and twelve.

An italic on the other hand is a variation of the character set that comprises the font, often times with additional calligraphy used to accentuate the slant.

Italics are an angled typeface with a distinct character set from its roman equivalent.

Obliques are just a geometrical transformation of the original font.

Italic vs oblique text
Italic vs oblique text

For italics to be displayed properly the user must have the italic version of the font installed.

If he doesn't, the text is simply skewered and an oblique effect is created on the fly.

As for which effect is best, the italic version is usually preferred by web developers but that's just convention.

Bold in CSS

Let's move on to the bold text effect.

Once again, the proper why to apply bold formatting is not through the HTML element <strong>.

The CSS property for bold text is font-weight.

There are quite a few values this property can take so let's start with the two main ones.

  • bold : the text will be displayed in bold.
  • normal : the text will be displayed normally (default).

Here is an example on how to make your paragraphs bold.

p { font-weight: bold; }

Nothing too complicated here.

CSS bold text
CSS bold text
What about the other values? You said those two were just the main ones.

In addition to bold and normal you can also use bolder and lighter which are respectively bolder and lighter than the inherited font weight.

There is also a third way of indicating a font weight, through numerical values.

  • 100 : Lightest.
  • 200 : Bolder than 100, lighter than 300.
  • 300 : Bolder than 200, lighter than 400.
  • 400 : Bolder than 300, lighter than 500. Equivalent of normal.
  • 500 : Bolder than 400, lighter than 600.
  • 600 : Bolder than 500, lighter than 700.
  • 700 : Bolder than 600, lighter than 800. Equivalent of bold.
  • 800 : Bolder than 700, lighter than 900.
  • 900 : Boldest.

While this method offers more options than the first one, these nine numerical values shouldn't be relied upon to apply a font weight consistently.

Many fonts contain fewer than nine bold variants, so unless you tested the font first I recommend you stick with bold and normal.

CSS font weight example
CSS font weight example

Underline in CSS

What about applying underline and other text styles?

The CSS property for this is aptly named: text-decoration.

It can take the following values.

  • underline : underlined.
  • line-through : struck through.
  • overline : a line above.
  • blink : blinking text. Seriously, don't use it. It doesn't even work on most browsers anymore.
  • none : normal (default).

The following CSS code will add an underline effect to the <h1> element and remove the default underline from any links on your web page.

h1 { text-decoration: underline; }

a { text-decoration: none; }

You can apply multiple values by separating them with spaces.

p { text-decoration: overline underline; }

p { text-decoration: overline underline line-through; }

Try it out and see the result for yourself.

I want to change the color of the underline. How can I do that?

Quite easily.

You can use the property text-decoration-color.

For its value just specify any color you want. By default it will be the same color as your text.

p {
    text-decoration: underline;
    text-decoration-color: red;
}

The above code will underline every paragraph in red without changing the color of the text.

Alignment and floats

There are two ways you can handle alignment in CSS.

You can either adjust the way the text is aligned within a block element, or you can modify the way the block element itself is aligned by having it float either to the left or to the right.

Text formatting with CSS
Text formatting with CSS

Alignment in CSS

CSS allows you to specify the way inline text is aligned within a block element.

Your text can be aligned either to the left, to the right, to the center or even configured to take up all the horizontal space available.

The CSS property used to define typographical alignments is unsurprisingly called text-align.

Here are the values it can take.

  • left : the text will be left-aligned (default).
  • center : the text will be centered.
  • right : the text will be right-aligned.
  • justify : the text will be justified.

Justified content simply means that the text any white space at the ends of lines.

Most books and other printed media have justified text.

Left-aligned vs justified text
Left-aligned vs justified text

Let's see the different alignments in action.

h1 { text-align: center; }

p { text-align: justify; }

.footer { text-align: right; }

The result is shown below.

The different CSS alignments
The different CSS alignments
You can't change the alignment of an inline element such as <span>, <em> or <a>. It must be used on either a paragraph <p>, a title <h1> or any other block element.

Floating items in CSS

There is another method of alignment in CSS called the float, commonly and more appropriately called text wrap.

Floats work in a different way than typographical alignment.

Whereas text alignments format only the content inside of a block element, floats affect the entire element.

The following image should give you an idea of how they're used on a web page.

Floating elements in CSS
Floating elements in CSS

As you can see, the image is floating to the right.

The CSS property you need to modify the float of an element is called... float. Who would have thought?

Here are the values it can take:

  • none : there is no float (default).
  • left : the element will float on the left.
  • right : the element will float on the right.

In theory, the float property can only be applied to a block-level element.

But that's not a problem since inline elements with a float will automatically be converted to a block layout.

You can therefore use float on any HTML tag you want: an image, a title, a paragraph and so on.

With that said, floats work best when the affected element has a defined width.

For our example we'll use an image.

A floating image

To apply a float to an image, or any HTML element, you first need the appropriate HTML code.

Here is what we'll use in our example.

<p><img src="siteraw.png" alt="Welcome to SiteRaw" /></p>

<p>Welcome to SiteRaw. SiteRaw is the best site on the web. Why is SiteRaw so awesome? And why do all your demos contain the same text?</p>

<p>Who knows...</p>
A common mistake is to place the floating element after the text. Whether you want it to float to the right or to the left, it must be above the text that surrounds it.

For now there is no CSS code, so you won't notice anything different.

Let's type the following in our CSS file.

img
{
	float: left;
}

And... that's it.

Just one property.

This code will make every <img /> tag float to the left.

If you want it to float to the right instead, just replace the value of the float property accordingly.

Clearing a float

When you insert a floating element, the text naturally wraps around it to one side or the other.

But what if you want some of your text to be underneath the floating element?

As you can see, in our example we have two paragraphs.

How can we make the second one not be affected by the image's float?

CSS has a property that allows you to do just that.

Elements affected by the clear property will automatically disregard any floating element and be moved down (cleared) below it.

Here are the values it can take.

  • left : the element is moved down after a left float
  • right : the element is moved down after a right float
  • both : the element is moved down after any type of float

In practice we'll be using mostly the third option.

Let's apply it to our demonstration.

First, the HTML code.

<p><img src="siteraw.png" alt="Welcome to SiteRaw" /></p>

<p>Welcome to SiteRaw. SiteRaw is the best site on the web. Why is SiteRaw so awesome? And why do all your demos contain the same text?</p>

<p class="siteraw">Who knows...</p>

Nothing very different from what we saw earlier, the only addition being the class identifier applied to the second paragraph.

Now for the CSS code.

img { float: left; }

.siteraw { clear: both; }

That's it.

The second paragraph should now start below the floating image as shown in the following figure.

Float and clear in action
Float and clear in action

You now know both methods to align elements in CSS.