Click here to Skip to main content
15,742,619 members
Articles / Web Development / HTML
Posted 1 Apr 2014


16 bookmarked

Beginner's Guide to HTML5 & CSS3 - Part 3 of 12

Rate me:
Please Sign up or sign in to vote.
4.93/5 (12 votes)
22 Aug 2016CPOL16 min read
Styling Your First Web Page

In the first two parts of this series, we took a brief walk through HTML's history and then looked at the basic structure of an HTML5 doucment. Then we examined the more common elements of HTML5.

With a basic understanding of HTML5, we can now turn to CSS. In this chapter, we will look at:

  1. Setting up a CSS Document
  2. Basic CSS Syntax
  3. Id and Class Selectors
  4. Backgrounds, Text, and Fonts
  5. Where and How to Use CSS

CSS stands for Cascading Style Sheet. The term "cascading" refers to the inherent design of CSS which allows the style of the document to be defined by the author, the browser, the reader, and even the display device, through one centralized process which allows the style wishes of each participant to come together, presumably like waters cascading into a singular river.

Setting up a CSS Document

A CSS document is a text file. In that file, we define rules that match elements on our web page and apply styling parameters to the elements' contents.

So, the first step is to open up your text editor and create a new file. Save this file as Beginner3.html. This will serve as the web page to showcase our styling. If you like, you can copy and paste the following into the document:

<!DOCTYPE html>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Beginner's HTML5 Part 3</title>
        <style type="text/css">
            i { 
                text-decoration: underline;
    <p>[Example of no styling]</p>
        <!-- Inline demonstration -->
        <h1 style="color: blue;">Inline</h1>
        <p style="font-family: Arial, sans;">
            Inline styling describes the method of placing CSS styles
            <i>directly into an element</i> in the web page.  All elements use
            the style attribute for this.</p> 

Feel free to add elements as you wish.

The second step is to create another new file and save it as part3.css. This file will hold our CSS rules. We will come back to this later.

For now, make sure your HTML5 file is saved and open it in the browser. It should look like this:

You will notice that the h1 element is colored blue, the font in the paragraph is different than the default font in the browser, and text between the opening and closing tags for the i element are displayed in italic and underlined.

Cool! Now that you see a tiny bit of what CSS can do, let's examine the syntax a bit.

Basic CSS Syntax

CSS exits in one of three states: Inline, Embedded, or External.


Inline styling occurs when you add CSS property definitions to the style attribute of an element. Here is the heading element from the example:

<h1 style="color: blue;">Inline CSS</h1> 

The style attribute is declared after the element name and before the closing bracket in the opening tag. In the case of this element, the style is set to "color: blue;".

The word "color" is a property, and the text "blue" is the value. These are separated by a colon and then terminated with a semicolon.

All elements can be styled by using the style attribute.


Embedding CSS means to create a style element in the head element of your web document and fill it with styling definitions. Here, you need to add two things to make it work: the selector and the curly braces.

In the file you created at the top of this article, there is an element called "style" inside the head element. In this style element, we have an embedded CSS definition. Here is the relevant text:

<style type="text/css">
    i { 
        text-decoration: underline;

The style tag holds the CSS definitions for this document. The type attribute, which is set to "text/css" defines the type of styling that the style element will contain. Because the browser can interpret the type of styling by merely looking at what you have typed, the declaration of this attribute is not necessary.

Also, the style element can appear just about anywhere in the document and it will work fine. However, a validated document must have the style element placed inside the head element (unless you specify the scoped attribute, but that is not covered in this series).


You are probably wondering what line "i {" means here. Well, the i part is called the "selector", and it is followed by a curly brace. Between that opening curly brace ('{') and a subsequent closing brace ('}') lies the CSS definition for the selector.

The selector is one or more patterns used by the browser to associate a style definition with one or more elements. The selector is not the same thing as a regular expression, but it does perform a similar function. The selector pattern will match elements based on:

  • element name (p, table, i, a, span, etc.) ,
  • element attribute id value,
  • element attribute class value,
  • the state of the element (checkbox checked e.g.),
  • the relationship of the element to other elements, or
  • a combination of the above.

In your CSS document, you can create selectors for each element type individually:

h1 {
    ...     /* properties and values for h1 elements */
p {
    ...     /* properties and values for p elements */ 
i {
    ...     /* properties and values for i elements */

Or you can combine them by separating the element names with commas:

h1, p, i, {
    ...     /* properties and values for h1, p, and i elements */

You can even select everything with the ever-powerful meta-character: the asterisk:

* {
    ...    /* properties and values for all elements */ 

In the code the "i" selector matches all i elements. If, instead, the i was replaced by "p", then the p elements in the web page would be assigned the styling.

So this (Notice the i is now a p...):

<style type="text/css">
    p { 
        text-decoration: underline;

Now gives this:

Notice that the paragraphs are now underlined. That is because the CSS selector "p" matched the p elements in the document and applied the text-decoration property of "underline".

Properties and Values

Just like with the way CSS is defined in the style attribute of all elements, the styling definitions between the curly braces begin with an property, followed by a colon (':'), then a value, and finally the semicolon (';').

p {
    text-decoration: underline;
- - - - - - - - - - - - - - - -
selector = p 
start definition = {
property = text-decoration 
value = underline  
end definition = } 


Unlike the inline and embedded CSS methods, the external method uses a separate file, usually called the CSS or styling document.

So, now that we have working embedded CSS code, let's put it into that new file we created earlier. This will be our external CSS document. Copy the text between the script tags and paste it directly into part3.css, then save the file. The contents of the CSS file should just look like this:

p { 
    text-decoration: underline;

Now we need to tell the web document where the style sheet is. To do that, we need to create a new element in our web page. To do this, get rid of the style attribute--tags and all--and replace it with the following:

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

The link element points to external files. Its rel attribute defines the type of resource in the link, and the href attribute contains the URL to the resource. Because it can point to many different types of resources, the rel attribute is required. When we are linking in CSS files, set rel to the value "stylesheet".

Make sure the href attribute is set to "part3.css" and the two files (part3.css and Beginner3.html) exist in the same folder.

Because our sample web page and the resource share the same directory, all the link element needs in the href field is the name of the file.

Here is what Beginner3.html should now contain:

<!DOCTYPE html>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Beginner's HTML5 Part 3</title>
        <link rel="stylesheet" href="part3.css">
    <p>[Example of no styling]</p>
        <!-- Inline demonstration -->
        <h1 style="color: blue;">Inline</h1>
        <p style="font-family: Arial, sans;">
            Inline styling describes the method of placing CSS styles
            <i>directly into an element</i> in the web page.  All elements use
            the style attribute for this.</p> 

Now, save everything. Bring the web page up in the browser. You should see a lot of underlined text if you changed the "i" to a "p" in part3.css.

With that, you now have a web page and an external stylesheet. When you make changes to the stylesheet and save it, you can just refresh the web page in the browser (usually the F5 button) and see your changes come to life.

Id and Class Selectors

The selectors in a CSS description which match an element name are called element Selectors. In this section, we will look at two other ways to select elements on the web page:


  • attribute id value
  • attribute class value


Id selectors match elements that have the same value for their id attribute. Class selectors match elements that have the same value for their class attribute.

Remember the global attributes? The id attribute holds a unique identifier for an element. The class attribute assigns a class value to an element. Only one element can have a given id value, whereas many elements can belong to the same class. Depending upon the structure of the document and your styling needs, one type of selector may work better than another.

The Id selector begins with a hash ('#') and is immediately followed by the id value. The Class selector begins with a period ('.') and is immediately followed by the class name. To wit:

#myuniqueid {       /* selects element with id of myuniqueid */
.myclassname {      /* selects all elements with class value of myclassname */
<p id="myuniqueid">This element is styled via id selector "#myuniqueid".</p>
<p class="myclassname">This element is styled via class selector ".myclassname".</p>
<span class="myclassname">This is also styled via the ".myclassname" selector.</span> 

Well, now that we have a good idea how to select elements on a page, we can take a look at what display features we can change for these elements.

Backgrounds, Text, and Fonts

Most elements have a background to them and can be set to a variety of things. We can kick things off by setting the background for the entire web page. Enter this new text into your CSS document:

body {
    background: lightskyblue; 

Now save the CSS file and refresh the page in the browser. You should now have a page with a blue background.

Even though we only set a color to the background, the background property can set much more. In fact, the background property lets you set all background-related properties on one line. This is generally what you can set:

background : color position repeat attachment image size origin clip 

Each property value is separated by one space. The CSS3-specific properties are size, origin, and clip; the others were defined in CSS1 and CSS2. If your browser does not fully support CSS3, the CSS3-specific properties may cause parsing errors. For now, we will focus on the color.


CSS colors can be defined in one of three ways:

  1. Keyword color
  2. RGB color
  3. Hexadecimal color

Keyword colors are a modified subset of the X11 colors (originally from the X Window System) which give you a good idea of what you will see by the name alone. The background color specified in the body selector above, 'lightskyblue', is just one of many pre-defined colors, each matched with a specific color value. Here is a small sampling:

AntiqueWhite #FAEBD7
Black #000000
Coral #FF7F50
DarkSeaGreen #8FBC8F
Gold #FFD700
LightSkyBlue #87CEFA
SandyBrown #F4A460
SteelBlue #4682B4

RGB colors use the rgb functional notation. The color values can be expressed as a decimal from 0 to 255 or a percent value.

background : rgb(0, 0, 255);        /* blue */ 
background : rgb(0%, 0%, 100%);     /* blue */ 
background : rgb(128, 128, 128);    /* gray  */ 
background : rgb(-23, 999, 0);      /* Green.  CSS is smart enough to clip values. */ 

Opacity is set to 100% by default, but it can also be changed by using a variant on the rgb notation: rgba. The fourth parameter, the alpha channel, must contain a float value between 0 and 1, inclusive:

background : rgba(135, 206, 250, .5)   /* lightskyblue with 50% opacity */ 
background : rgba(53%, 81%, 98%, .5)   /* same thing, but using color channel pcts */ 

Hexadecimal colors are expressed as a hash character ('#') followed by three or six digits. If three, then the resultant is made by replicating each digit. So, #3c9 actually represents #33cc99:

background : #00f;          /* blue */ 
background : #0000ff;       /* same thing: blue */
background : #87cefa;       /* hexadecimal value for lightskyblue */   

There is also one special color called 'transparent'. It makes the background of the element invisible.

background : transparent    /* equivalent to rgba(0,0,0,0)  */ 


How about images? CSS uses a url functional notation to point to an image file. Here is how you may specify an image in the same directory as the web page:

body {
    background: url('bkg_1.jpg'); 

Images in backgrounds are, by default, tiled. Here is how you can show just one iteration of an image in a web page background in the upper-left corner of the page:

background: url('bkg_1.jpg') top left no-repeat;

The order of the values in the background property is not set in stone. Care must be taken, however, with the position property. The values are word pairs that must be specified in the correct order:

Property Values
background-position left top
  left center
  left bottom
  right top
  right center
  right bottom
  center top
  center center
  center bottom
  xpos ypos (pixels or percent values)

There are assumed and unwritten standards most people follow, either because they have always done things a certain way or they have learned from their mistakes. One such standard is the suggestion that the CSS author always include a color property with an image when defining a background:

body {
    background: url('bkg_1.jpg');
    background-color: lightskyblue; 

The reasoning is simple: If the image goes away or cannot be loaded, you will always have a color to display as your backup plan, because there is nothing in a web page that indicates a missing background image file.

Containing Text

Before discussing fonts and text, it would be helpful to first look at three ways text can be isolated.

  1. Paragraphs (p element)
  2. Blocks (div element)
  3. Inline (span element)

The p element has already been covered. It groups a specific amount of text, visually separating it from the rest of the document with margins above and below the element.

But, there are many cases where margins are not wanted, or the text needs do be constrained within a specific area on the web page. Paragraphs (using the p element) cannot be set to a certain width or height, because the p element is not a block element. Block elements can be constrained by width and height, meaning the contents of the block element can be constrained as well.

The div element is one such block element.


There are no special attributes associated with a div. However, a div's position and size can be controlled via CSS definitions. This makes the div a very good element to use when text must be isolated or constrained in some fashion.

<div style="width: 220px;">
    Block elements can be positioned and sized.  The div element is
    an excellent example of a block element.  Prior to HTML5, it
    was used as the go-to element for web designers who opted to
    stay away from tables and frames in their designs.  This text
    is constrained by a div that is 220 pixels wide.

The above code shows text inside a div element that has a width of 220 pixels. Because the div is constrained, all lines of text inside the div will not exceed 220 pixels in width. This is what it looks like in the Chrome browser:

The span element, on the other hand, is similar to the p element in that it cannot be sized, but it does not separate its contents from the rest of the document in any visible manner, unless it has a styling change.

Here is some code with two span elements. One has no styling and the other does. (Note we are using inline styling here.)

<div style="width: 300px;">
    This is some text <span>with part of it wrapped
        in a span element.</span> Notice the browser
        does not indicate anything special.</p>
    This is some text <span style="color: green;">with part of it wrapped
        in a span element with CSS styling.</span> Notice the browser
        shows a change in text color.</p>

When rendered, the browser shows a change in the text only with the span which has styling:

The div and span elements can be used to modify the appearance of text via CSS properties. Let us now take a look at how other text properties can be changed.

Text and Font Properties

Text on a web page is displayed in a font with text decoration properties. Without a custom CSS selector, the browser controls the default font, size, and decorator values. CSS gives you the ability to display text in many different ways, enabling your pages to override the defaults.

The font properties are as follows:

Font Property Example Values
font-family Arial, Helvetica, sans
font-style normal, italic, oblique
font-variant normal, small-caps
font-weight normal, bold, 700
font-size 20pt, larger, 1.2em, 150%

There are also a few system font names that can be used to specify a font:

System Font Description
caption captioned controls (button, etc)
icon icon labels
menu font used in menus
message-box dialog boxes font
small-caption labels for small controls
status-bar window status bar font

Here is an example of specifying various font properties for a web page:

body {
    font-family: Helvetica, Arial, sans;
    font-style: italic;
    font-variant: normal;
    font-weight: normal;
    font-size: 12pt; 

There is a shorthand way to set font properties:

font: font-style font-variant font-weight font-size/line-height font-family

When using the shorthand, any properties not specified default to normal. For example, the following does the same thing as the declaration above:

body {
    font: italic 12pt Helvetica, Arial, sans; 

Note the comma-separated list for font-family. CSS interprets this list as a request; the most important on the left and the least important on the right. If the first font in the list is not available, CSS checks the next font. The list is traversed like this until a valid font is found on the client system.

If, for example, we don't have Helvetica loaded on our system, but we do have Arial, then the body declaration above will cause text in the body to be shown in Arial font.

There are also a few generic font names that can be used to represent a font defined in the user agent:

  • serif
  • sans-serif
  • cursive
  • fantasy
  • monospace

When specifying fonts in CSS, it is a good idea to use one of these generic names as the last choice. If no fonts in a list match, a default font will be used based on the generic font name (assuming a generic is listed). If no generic has been defined in the list, then the browser will use its own default.

Text presentation can also be altered using properties. Here is a list of the available choices:

Decoration Property Description
text-indent value to indent first line of text
text-align describes horizontal alignment of text
text-decoration decorates text using text color
text-transform controls capitalization effects
letter-spacing defines spacing between characters
word-spacing defines spacing between words
white-space defines how white space is handled

The text-indent and text-align properties are demonstrated in the following:

<div style="width: 240px; text-indent: 30px;">
    Notice how the first line of text in this div element
    is indented 30 pixels. Alignment defaults to the left.
<div style="width: 240px; text-align: center;">
    This text is<br />centered.<br /> Line breaks have been added to
    empasize the alignment.  Also note the lack of space
    between these two divs, unlike the spacing feature of
    the p element.

Where and How to use CSS

When CSS was young, browsers did not implement a lot of its features and web designers made due with elements like <font> and <blink>. Fast forward to today, and you will find CSS just about everywhere.

To be clear, let us take a look at what CSS can not do:

  • Make your site more informative (It all comes down to content.)
  • Make your pages display faster (Sorry, but that's usually a bandwidth thing.)
  • Make you rich (If it did, there would be a lot more millionares in this world.)
  • Solve your personal problems (Dude...really...CSS?)

CSS is all about style, and style should come after structure and substance.

So, here is a recommended order of operations:

  1. Nail down the vision. You may have an idea for a cool site, but all you can see in your head is a cool blue background and spacey font text wrapped around awesome pictures. Unfortunately, if all you can envision for a web page is color and font, then you need to get cracking on foundational work. The "vision" is the reason for its existence and the thing it is trying to accomplish.
  2. Make a sketch or two. All the best artists make sketches before applying inks. Taking the pictures out of your head and putting them on paper gets you focused on reasonable goals.
  3. Create your HTML5 code with no CSS. Yes, this sounds like torture, but the purpose of creating the bland content is twofold:
    1. You get the substance formed without any styling distractions.
    2. You create the semantics first, which seriously helps organize the content.
  4. Make it pretty with CSS.

One other recommended procedure I like to impress upon impressionable folk is:

Always use external CSS files.

The author recommends this, because you can have your CSS file open in a text editor while the web page is up in a browser window, make changes, and refresh with F5 (or whatever your browser uses). The changes will update right away and you can go through iterative changes very quickly.

The big plus here is even more apparent for those of us who create web pages that are compiled from some other source code like C# or Java. With CSS, you will not need (usually) to re-compile the code over and over for each little styling change.

Oh, and the second plus lies with standardization. By this, I mean to say that external CSS files act as templates when the classes and definitions are repeated on all the pages in a web site. Making changes to embedded CSS code across many files usually leads to embarassing errors.


Well, that's a bit of a scratch upon the surface of what CSS has to offer. This chapter introduced you to the simple syntax of CSS and a handful of useful properties.

In the next chapter, we will walk the talk and go through the process of designing a web page: vision, sketch, coding, and styling.


2014-04-01: Initial posting.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer (Senior)
United States United States
I am an experienced developer, having spent my first 17 professional years in various Unix-like environments, following up with Windows since 1998. I have worked in web development teams since 2001, focused initially on Java but now fully settled into the .NET world. I have written production-value code in 8086 assembler, (various forms of) BASIC, Pascal, xnix shell (korn, mostly), C, C++, C#, and Java. When I code for fun at home, I usually play with Delphi, but I also keep an eye on Python because my friends keep telling me how cool it is.

Comments and Discussions

QuestionMy vote of 5 Pin
B Jefferson16-Apr-14 5:44
B Jefferson16-Apr-14 5:44 
AnswerRe: My vote of 5 Pin
James Jensen21-Apr-14 10:50
professionalJames Jensen21-Apr-14 10:50 
QuestionNice Mr.. Pin
Gun Gun Febrianza12-Apr-14 8:30
Gun Gun Febrianza12-Apr-14 8:30 
AnswerRe: Nice Mr.. Pin
James Jensen21-Apr-14 10:48
professionalJames Jensen21-Apr-14 10:48 
QuestionSome suggestions... Pin
Kornfeld Eliyahu Peter1-Apr-14 19:33
professionalKornfeld Eliyahu Peter1-Apr-14 19:33 
AnswerRe: Some suggestions... Pin
James Jensen2-Apr-14 3:51
professionalJames Jensen2-Apr-14 3:51 
SuggestionSuggestion Pin
Ranjan.D1-Apr-14 15:49
professionalRanjan.D1-Apr-14 15:49 
GeneralRe: Suggestion Pin
James Jensen2-Apr-14 3:44
professionalJames Jensen2-Apr-14 3:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.