Introduction to HTML and CSS

INTRODUCTION

This workshop is intended to give an overview or perhaps a review of HTML and CSS, presented as the fundamental building blocks for designing and developing websites. The workshop will be divided into the following modules:

  • Getting Started
  • Introduction to HTML
  • Intro to CSS
  • CSS Layout

GETTING STARTED

Preliminary Background

  • What constitutes a website, where is it stored?
  • The Browser is your friend for web development
  • What do we use to build a website
  • Why is learning HTML from scratch useful?

Writing and running your first web page

  1. Create a folder labelled web_workshop_Intro_2016 on your desktop
  2. Inside your folder, create a folder called practice
  3. Inside the practice folder, create a file called index.html
    Why is calling it index.html a good idea?
  4. Open the index.html in your text editor and write “This is my first web page.”
    Save the file.
  5. Open the file in your browser. You just made and viewed your first web page!

Note:

  • It is important that the extension “.html” is specified – some text editors, such as Notepad, will automatically save it as “.txt” otherwise.
  • You also need to ensure that your file is being saved as plain text. TextEdit, for example, will start new files by default as “rich text”, containing lots of formatting extras. In this case: go into the preferences of your text editor and make sure you check the plain text format option before creating a new file.
  • As you have just witnessed: to view at HTML files, they don’t need to be on the web (some public server somewhere).
  • Instead of double clicking on the file you could also type in the local address of the index.html file in the browser’s address bar (where you would normally type in a public url).

Basic Terminology: HTML and CSS

HTML is a hypertext markup language. Hypertext means “text with links in it.” Any time you click on a word that brings you to a new webpage, you’ve clicked on hypertext. We need to use HTML in order to give the content structure & meaning. A markup language is a programming language used to make text do more than just sit on a page: it can turn the markup into images, links, tables, lists, forms and much more.

CSS: cascading style sheets, is a presentation language created to give the content style and appearance.
Importantly, CSS is not a part of the HTML markup language, rather it is implemented independently of the HTML Markup.

Example: Distinguish between HTML and CSS:

  • The HTML p element is used to display a paragraph of text on a web page. The p element is specifically used here as it provides the most value for the content (is most indicative in terms of semantics and structure of the content).
  • CSS then uses a type selector (we will discuss definitions later) of the p element in order to determine the color, font size, font weight, and other stylistic properties of the paragraph.

Common HTML Terms:Tags, Elements and Attributes

  1. Elements: HTML Elements are define specific and well defined “objects” within a page, including structure and content. Some of the popular elements include h1-h6, p, a, div, span, strong, and em.
  2. Tags: Elements are often made up of multiple sets of tags, identified by opening and closing tags. Opening tags mark the beginning of an element, such as <div>. Closing tags mark the end of an element and begin with a forward slash, such as </div>.
  3. Attributes: Attributes are properties used to provide additional instructions to given elements. More commonly, attributes are used to assign an id, class, or title to an element, to give media elements a source: src, or to provide a hyperlink reference href.

Common CSS Terms:

  1. Selectors: A selector determines exactly which element, or elements, the corresponding styles will be applied to. Selectors can include a combination of different IDs, classes, types, and other attributes – all depending on the level of specificity required.Selectors can be identified as everything that comes before the first curly brace,”{“.
    Example: p { . . . } – Here: The “p” is the selector.
  2. Properties: A property determines the style that will be applied to an element. Properties can be identified as the text coming immediately before a colon. There are an abundant number of properties you can use, and new ones are continually being added to the language.
    Example: p { color: #ff0; font-size: 16px;} – Here: “color” & “font-size” are the properties.
  3. Values: A value determines the behavior of a property. Values can be identified as the text in-between the colon and semicolon
    Example: p { color: #ff0; font-size: 16px;} – Here: “#ff0” & “16px” are the values.

The aforementioned HTML & CSS Terms have been defined but: we have not yet discussed how and when to use them. In the following sections we will go into detail on how to do exactly that!

INTRODUCTION TO HTML

Basic Structure of an HTML Document:

All HTML documents have a required structure that includes the following declaration and tags: doctype, html, head, and body. Once you have the generic html structure, you will then include any additional HTML elements, tags and attributes which will wrap around the content and apply meaning and structure to it.

Change your index.html document so that it looks like this:

1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html>
<head>
<title> This is the title of my first web page </title>
</head>
<body>
    This is my first web page.
</body>
</html>

Now save the index.html again, go back to the web browser and reload the page.

The appearance of the page will not have changed at all, but the purpose of HTML is to apply meaning and structure , not style or layout. Therefore, this example has now defined some fundamental and necessary HTML elements of a web page:

  • The first line on the top, <!DOCTYPE html > , is a document type declaration and it lets the browser what language it’s reading (in this case, HTML5). It is very important to declare this – if you don’t, browsers will have to do extra work to determine the type of page you are trying to load.
  • <html> is the opening tag that kicks things off and tells the browser that everything between that and the </html> closing tag is an HTML document.
  • Within the <html>tags there are always two parts to the resultant html code: the head and the body tags.
  • The head tags consist of an opening & a closing tag and includes important information about the webpage, such as its title, meta data, links to external files etc… The title are the words we see in the tab (for example, the title of this page is “This is the title of my first web page”).
  • Any content within the body tags (open and close) will be what is displayed on the actual page. The body tags go inside the html tags, but not inside the head tags.

Adding HTML elements into an HTML document:

Now that we have our basic html page set up, we can now add other elements to it.

The p tag:

Add the following line to your html page (within the body tags after the first line of text):

1
How exciting

Save and reload the html page in your browser:
You might have expected your document to appear as you typed it, on two lines, but instead you should see something like this:
This is my first web page. How exciting.

This is because web browsers don’t usually take any notice of what line your code is on. It also does not take white space into account: – you would get the same result if you typed “This is my first web page.   How exciting”).

So: If you want text to appear on different lines or, rather, if you intend there to be two distinct blocks of text (remember, HTML is about meaning, not presentation), you need to explicitly state that.

Change your two lines of content so that they look like this:

1
2
<p>This is my first web page.</p>
<p>How exciting</p>

Now when you reload the page, you see something different… Why? Because the p
tag is an HTML tag used specifically for paragraphs – and when the content is place within this tag – the content will be structured as required…

Emphasis of text:

You can emphasize text in a paragraph using em (emphasis) and strong (strong importance).
Example:

1
<p>Yes, that really <em>is</em> exciting. <strong>Caution:</strong> let's not get too excited yet - we have not even started with CSS!</p>

Line Breaks and the creation of white space:

The line-break tag can also be used to separate lines like this:

1
<br \>

As there is no content involved with the break space tag – we use the convention to open and close the tag simultaneously.

We can also create white space using the following code:

1
&nbsp;

Headings

P tags are just the start for giving your content structure. If you want real headings in your html document then we have HTML tags for that:
h1 – h6 where h1 is the most superior and h6 the least.
Change your index.html page to the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
<head>
    <title>This is the title of my first web page</title>
</head>
 
<body>
    <h1>My first web page.</h1>
 
     <h2>What this is?</h2>
    <p>A simple page put together using HTML in February 2016.</p>
 
    <h2>Why this is?</h2>
    <p>To learn how to build a website using basic HTML components!</p>
</body>
</html>

Save and reload the html page in your browser.
Note: you should use headings consistently – h1 should be used as the main heading, h2 as a sub heading, h3 as a sub-sub heading etc…

Lists:

In HTML lists are fundamental elements – i.e. when we want to create a menu (navigation). In this workshop we will discuss two types of lists: ordered and unordered :
Unordered and ordered lists are defined and used in a similar manner, the only difference being that unordered lists are non sequential and are preceded by bullets, whereas ordered lists are sequential and are usually preceded by numbers.

Unordered Lists:
The ul tag is used to define unordered lists.
Inside the list: the li tag is used to define each list item.
Change your index.html to the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
<head>
   <title>This is the title of my first web page</title>
</head>
<body>
   <h1>My first web page.</h1>
 
     <h2>What this is?</h2>
    <p>A simple page put together using HTML in February 2016.</p>
 
    <h2>Why this is?</h2>
    <ul>
        <li>To learn HTML</li>
        <li>To build beautiful layouts using CSS</li>
        <li>To do some fancy effects using javascript</li>
    </ul>
</body>
</html>

A brief note regarding changing the type of bullets used for unorderd lists: The CSS list-style-type property is used to change these:
Changing bullets to square bullets:

1
<ul style="list-style-type: square">

Changing bullets to open circle bullets:

1
<ul style="list-style-type: circle">

Changing bullets using a custom image:
For this example: make a folder called images inside the practice folder and save the following image to that folder:bird_redS

1
<ul style="list-style-image:  url(images/bird_redS.png)">

Eliminating bullets all together:

1
  <ul style="list-style-type: none">

Small Exercise: How could we just change the style of one list item at the time – rather then all at once?

Ordered Lists:
The ol tag is used to define ordered lists.
Inside the list: the li tag is used to define each list item.
Change the index.html page to the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
<head>
   <title>This is the title of my first web page</title>
</head>
<body>
   <h1>My first web page.</h1>
 
     <h2>What this is?</h2>
    <p>A simple page put together using HTML in February 2016.</p>
 
    <h2>Why this is?</h2>
    <ol>
        <li>To learn HTML</li>
        <li>To build beautiful layouts using CSS</li>
        <li>To do some fancy effects using javascript</li>
    </ol>
</body>
</html>

Again, we can use the CSS list-style-type property is used to change the numbering style from the default, i.e. decimal to lower roman numbers, with the value lower-roman:

1
<ol style="list-style-type: lower-roman">

More properties are possible: see : w3-schools

Nesting lists:
Lists can also be included in lists to form a structured hierarchy of items.
Replace the above list code with the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<html>
 
<head>
   <title>This is the title of my first web page</title>
</head>
 
<body>
   <h1>My first web page.</h1>
 
     <h2>What this is?</h2>
    <p>A simple page put together using HTML in February 2016.</p>
 
    <h2>Why this is?</h2>
		<ul> 
        <li>To learn HTML</li>
        <li>To build beautiful websites using:
        <ol>
        	<li>Colors</li>
        	<li>Grid layouts</li>
        	<li>Custom type faces</li>
        	<li>And much more...</li>
        </ol>
        </li>
        <li>To do some fancy effects using javascript</li>
    </ul>
 
</body>
</html>

Save and Reload the page – now breathe.

Links:

So far we’ve built one web page with no hyperlinks — but the whole point is to be able to connect (or link) to other pages, images and many other resources on the internet…
So lets look at how to create links:
An anchor tag (a) is used to define a link, however:: you also need to add something else to the anchor tag – the destination of the link – which is an attribute of the anchor tag.
Add the following markup to your index.html page:

1
2
<h2>Where to find the computation lab website?</h2>
<p><a href="http://clab.concordia.ca">Concordia Computation lab</a></p>

The destination of the link is defined in the href attribute of the tag. The link can be absolute, such as “http://clab.concordia.ca”, or it can be relative to the current page:
If, for example, you had another file called “myfavoritePhotos.html” in the same directory then the line of code would simply be (just an illustration…)

1
<a href=""myfavoritePhotos.html">Link to view my favorite photos</a>

Note: A link does not have to link to another HTML file, it can link to any file anywhere on the web.
Finally:- A link can also send the to another part of the same page they are on. You can add an id attribute(don’t worry – we will discuss this more later) to just about any tag.
For example, lets add an id attribute to our (ul) tag in our index.html page:

1
<ul id ="myList">

and then link to it by placing this just after the opening body tag:

1
<a href="#myList">Go to list</a>

Selecting this link will scroll the page straight to the element with that ID.

Images:

As we know, the web is not just about text, it is capable of displaying multiple forms of multi-media, the most common being images:
The img tag is used to put an image in an HTML document and it looks like this:

Go find at least one image, put it in your “practice” folder and place it in the html page using the following template:

1
img src=<name_of_your_image.jpg> width=<image_width> height=<image_height> alt=<text_based_description_of_image>>

The src attribute will tell the browser where to find the image. Like the (a) tag, this can be absolute (i.e. an address to a specific url), but is usually relative (like the above example).

The width & height attributes are necessary because if they are excluded, the browser will tend to calculate the size as the image loads, instead of when the page loads, which means that the layout of the document may jump around while the page is loading.

Finally, the alt attribute is the alternative description. This is an accessibility consideration, providing meaningful information for users who are unable to see the image.
Note that, like the br tag, because the img element does not enclose any content, and therefore no closing tag is required.

Forms:

Forms aren’t usually necessary nor helpful, unless they are used in conjunction with a programming language to process the information inputted by the user. The creation of these scripts is beyond the scope of this workshop as they require languages other than HTML and CSS. Rather, we will focus here on designing and using the HTML GUI elements required for forms.
The basic tags used in the actual HTML of forms are form, input, textarea, select and option.

The form element:

form defines the form and within this tag, if you are using a form for a user to submit information (which we are assuming at this level), an action attribute is needed to tell the form where its contents will be sent to.

The method attribute tells the form how the data in it is going to be sent and it can have the value get, which is default, and latches the form information onto a web address, or post, which (essentially) invisibly sends the form’s information.

These scripts take all manner of guises that are largely outside of the remit of this website because they require languages other than HTML and CSS.

Breather: A smallish exercise

Lets take a break from the lecture part of the workshop: – and lets do an exercise:

Recreate the following example html page (will be projected) – using ONLY the tags+elements+attributes that we have learnt so far… (no css, no div tags etc..)

Note: the link points to: http://www.petplanet.co.uk/small_breed_profile.asp?sbid=6
& the image is available at: http://www.pocanticohills.org/4thgrade/06/dwarfloprabbit.jpg”

Bonus** how could we modify the hyperlink – to open in a new window as opposed to the same window?

Solution to the Exercise

Div and Span

HTML is all about applying meaning to content. Whereas most HTML tags apply meaning (i.e. “p” makes a paragraph, “h1” makes a heading etc.), the span and div tags apply no meaning at all. This might sound utterly useless right now – however they play a very important role when it comes to applying a layout to your webpages with css…. Also, they are used to group together (act as containers for) a chunk of HTML elements in a logical manner.

A span element is in-line and usually used for a small chunk of HTML inside a line (such as inside a paragraph).

Inline elements in general, do not begin on a newline and fall into the normal flow of the document. An inline element CANNOT nest a block element, but can wrap other inline elements.

Example inline elements:

1
<span>, <em>, <strong>, <td>, <a>, <img> etc..

A div (division) element is block-line (which is basically equivalent to having a line-break before and after it) and used to group larger chunks of code.

Block elements always begin on a newline, and occupy the available width. Block elements may nest each other and can wrap inline elements as well.

Example block elements:

1
<div>, <h1>, <p>, <ul>, <table> etc...

Note: all elements in HTML are either block or inline.

Let’s make a new html page – we will be using this new page for testing our css – as we are soon coming to “that” part of the workshop … name the file something like “index2.html” – and copy the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html>
  <head>
	<title> Example Sections </title>
  </head>
  <body>
  <!-- div vs spans -->		
  <p>Just a paragraph not nested in a div</p>
  <p>Just another paragraph not nested in a div</p>
  <!-- div vs spans -->		
  <!-- div -->
  <div>
     <p>Paragraph (Block level) nested in a div</p>
     <p>Another paragraph inside a div.</p>
     <a href ="http://clab.concordia.ca" target ="_blank"> link inside a div tag to clab </a>
</div>
<div>
     <p>Paragraph (Block level) nested in a div</p>
     <p>Another paragraph inside a div.</p>
</div>
<!-- span -->
<p>Paragraph not in a div<span> text inside a span tag</span> cont paragraph after span.</p>
</body>
</html>

Note: the resulting page does not look very interesting – but as you can see, so far the div and span tags have not seemed to add any “structure” to the content… Let’s wait and see…

HTML 5 tags

Before ending our discussion of HTML elements, lets quickly go over some useful “new” HTML 5 elements. All of these “new” elements are focused around improving semantics (refining the meaning associated with using the HTML element). Before, if you wanted to declare a block level section of a page you were likely to use a div. With HTML5 you have a handful of new block level elements that allow you to write more semantic code…

html5(http://learn.shayhowe.com/html-css/elements-semantics)

The header, is used to identify the heading of a page, article, section, or other segment of a page. In general, a header may include a heading, introduction text, or navigation. You can use more than one header on a page. Depending on the website, you should include a header at the beginning of the page. Additionally, a header may reappear as the header of an article or section as necessary.

The nav is a block level element used to denote a section of major navigational links on a page. Not all links should be wrapped within a nav element. The nav should be reserved for primary navigation sections including universal navigation, a table of contents, breadcrumbs, previous/next links, or other noteworthy groups of links.

The article block level element is very similar to that of a div or section element, however it is specifically defined as an element which should include independent, self-contained content. Most often the article element will fall within blogs and other publishing websites as a block of published content.

A section element is more likely to get confused with a div than an article. As a block level element, like a div,a section is defined to represent a generic document or application section. Where a section differentiates itself from a div is that a section is not to be used as a convenience for styling or scripting purposes. (However::: you can choose to use it for such purposes…)

To accompany the header and footer elements there is also the aside block level element. An aside defines content related to the document or section surrounding it. As with header and footer elements, the aside can be used multiple times per page, so long as each use is practical.

*** Keep in mind that the aside is a block level element, in which it will appear on a new line and occupy the full width of the page or any container.
If you would like to get the aside to appear to the right or left of a block of content you will need to float the aside element (using css -which we are coming to…).

The footer is identical to that of the header however for the bottom of a page, article, section, or other segment of a page. A footer should not stem away from the document or section at hand and its context should include relative information.

The following HTML example is designed using HTML 5 tags. Notice when you run the page in your browser, how these elements won’t alter the appearance of text, but are used to help style content using CSS.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!DOCTYPE html>
<html>
<head>
	<title>HTML5 Markup</title>
 
	</head>
	<body>
	<header>
	 <h1>This page is marked up with HTML 5 tags</h1>
		<h2>The tags used are for semantic purposes... </h2>
	</header>
	<aside>
		<h3>News of the day:</h3>
		<p>This text is inside the aside element. It is secondary to the main content on the page.</p>
	</aside>
	<aside>
		<h3>More News of the day:</h3>
		<p>This is a second aside element.</p>
	</aside>
	<nav><p>Some Navigation inside the nav element</p> <p>About Us</p>
		<p>Our Products</p>
		<p>Contact Us</p>
	</nav>
	<article>
		<h3>The main text inside an article tag</h3>
		<section>
		<p> The first part of the main content</p>
		</section>
		<section>
		<h3>A header for the second part of the main content</h3>
		</section>
	</article>
	<footer>
		<p>This page was created by the clab</p>
	</footer>
	</body>
	</html>

Video in HTML 5

Adding in HTML5 videos requires us to use the video HTML element. The following example specified adding an mp4 to the HTML page:

1
2
3
<video width="320" height="240" controls>
  <source src="movie.mp4" type="video/mp4">
</video>

The src attribute of the (src) tag, specifies (like with images) the location of the video.

The controls attribute adds visual video controls, like play, pause, and volume. Other attributes that may be used, the most popular of which include autoplay, controls, loop, and preload. Note: With videos, not specifying the controls attribute shows the video, however doesn’t provide any way to play it unless the autoplay Boolean attribute is also applied. Best practice here would be to include the controls attribute unless there is good a reason not to allow users to start, stop, or replay the video.

It is also a good idea to always include width and height attributes. If height and width are set, the space required for the video is reserved when the page is loaded. However, without these attributes, the browser does not know the size of the video, and cannot reserve the appropriate space to it. The effect will be that the page layout will change during loading (while the video loads).

Applying audio in HTML5 is very similar to adding video except we use the audio HTML element.

Lastly – the HTML5 canvas element is possibly the most interesting of the new features of HTML5. However – in this workshop we will not have time to cover it – but if you are interested in i.e. drawing etc … have a look at the possibilities when using the HTML5 Canvas…

INTRODUCTION TO CSS

How to call CSS in HTML

There are three ways to apply CSS to HTML: in-line, internal and external:

IN-LINE STYLES
in-line styles are placed straight into the HTML tags using the style attribute. We already have seen such an example when we applied a bullet style to our lists.
An example of adding a specific style to a paragraph could be:

1
<p style="color: red">text</p>

This would render all text in the paragraph to be red.

Applying in-line styles is not a good practice: Remember a better approach is that the HTML should be a stand-alone, presentation free document, and so in-line styles should be avoided wherever possible…

INTERNAL STYLES
Internal styles (also known as embedded styles) are used for the whole HTML page. You place the CSS inside the head element, and then wrap the HTML style tags
around all of the styles for the page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
<head>
<title>CSS Example</title>
<style>
 
    p { color: red;}
 
    a {color: blue; }
 
</style>
...
</head>
<body>
...
</body>
</html>

In the above example all text within any paragraph tag will be red, and any text within any (a) tag will be blue.
This option is better than in-line styles – however when building a website it is usually the case that we will have more than one HTML page. Thus, with this option, we would need to copy+paste the styles in every HTML page — which can become quite redundant – so let’s look at the last option:

EXTERNAL STYLES
External styles are used for the whole, multiple-page website. There is a separate CSS file, which will simply look something like:

1
2
3
 p { color: red;}
 
 a {color: blue;}

Then, if this file is saved as “style.css” in the same directory as your HTML page then it can be linked into any HTML page by defining the (link) tags inside the head element like this:

1
2
3
4
5
6
<!DOCTYPE html>
<html>
<head>
    <title>CSS Example</title>
    <link rel="stylesheet" href="style.css">
...

Applying CSS to HTML

For this workshop, lets use an external style sheet – so in your text editor create a new file and save it as “style.css”. Don’t worry about linking it yet to an HTML page – we will first define some styles…

Selectors, Properties and Values
These terms were briefly mentioned in the introduction – however now we will learn how to define and use them:
Where HTML has tags, CSS has selectors. Selectors are the names given to styles in internal and external style sheets.
In this Workshop we will focus first on HTML selectors, which are simply the names of HTML tags and are used to change the style of a specific type of element.
For each selector there are properties inside curly brackets, which simply take the form of words such as color, font-weight or background-color…

A value is given to the property following a colon (NOT an “equals” sign) and semi-colons separate the properties.
If we add the following to our style.css:

1
body { font-size: 14px; color: navy;}

We are specifying that all text in the body tag will be 14 pixels and be navy in color.
Now if we go back to our “index2.html” – remeber the one with the divs? and link the style sheet in:

1
2
3
4
5
6
<!DOCTYPE html>
<html>
<head>
    <title>Example Sections</title>
    <link rel="stylesheet" href="style.css">
...

What happens when we reload the page? – All the text is blue and 14px – why? Because all the text is within the body tag… and since we have not yet defined any other styles for other HTML element – this style is applied to anything within the body tag.

COLOR
Lets quickly side track to a quick discussion on color:

CSS brings 16,777,216 colors to your disposal. They can take the form of a name, an RGB (red/green/blue) value or a hex code.

The following values, to specify a full red color will all produce the same result:

  • red
  • rgb(255,0,0)
  • rgb(100%,0%,0%)
  • #ff0000
  • #f00

Predefined color names include aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, orange, purple, red, silver, teal, white, and yellow.
Transparent is also a valid value.
Note: CSS3 also allows for HSL colors (HUE, Saturation and Lightness) along with semi-transparent colors – not discussed in this workshop…

Colors can be applied to HTML in 2 ways: by using the color & background-color properties.
Therefore to create a style for the h1 element whereby it has a blue background with yellow text could be implemented as:

1
h1 {color: yellow; background-color: blue;}

Place this line in your style.css page and run the index2.html page. Any change? No – Why? Because we have no h1 elements in our HTML page!

So put one in – save the page and reload.

1
<h1> Example Heading </h1>

What happened? Now since we have a style defined for the h1 tag – the style will be applied to the h1 element – even though this element is also within the body. Note: why is it that the background stretches to the width of the page? How can we control this?

Small Exercise: change the body background color to grey.

A very useful link to finding out about HTML colors: HTML-Color Picker

TEXT
Another side discussion involves how to alter the size and shape of text on a webpage. We have done that very simply so far by using the font-size property in the body style – but there are a vast number of other properties which also allows for one to control text:

  • font-family: This is the font itself, such as Times New Roman, Arial, or Verdana. The user’s browser has to be able to find the font you specify, which, in most cases, means it needs to be on their computer so there is little point in using obscure fonts that are only sitting on your computer!
    There are a select few “safe” fonts (the most commonly used are Arial, Verdana and Times New Roman), but you can specify more than one font, separated by commas. The purpose of this is that if the user does not have the first font you specify, the browser will go through the list until it finds one it does have.
    Therefore: if one specifies font-family: “arial”, “helvetica”,”serif”, the browser will look for the Arial font first and, if it can’t find it, it will search for Helvetica, and then a common serif font.
  • font-weight: states whether the text is bold or not. Most commonly this is used as font-weight: bold or font-weight: normal but other values are bolder, lighter, 100, 200, 300, 400 (same as normal), 500, 600, 700 (same as bold), 800 or 900.
  • font-style: states whether the text is italic or not. It can be font-style: italic or font-style: normal.
  • text-decoration: states whether the text has got a line running under, over, or through it:
    text-decoration: underline – makes underlined text.
    text-decoration: overline – places a line above the text.
    text-decoration: line-through puts a line through the text.
    This property is usually used to decorate links and you can specify no underline with text-decoration: none.

Small exercise: apply a font-family property to your body style. Then apply a text decoration style to your p tag.
If you want more possible properties for text (i.e. text spacing – a small overview is available at w3schools.

STYLING LINKS WITH CSS

We have currently one link in our index2.html page. Right now there is no indication of which state the link is in. We only know that it is a link because by default any text within an “a” tag will be underlined.
There are actually 4 states to links specified by an “a” tag:

  1. a:link – a normal, unvisited link
  2. a:visited – a link the user has visited
  3. a:hover – a link when the user mouses over it
  4. a:active – a link the moment it is clicked

Therefore, we can apply styles to each one of these states individually. The following example illustrates some options:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* unvisited link */
a:link {
    color: red;
    background-color:white;
}
 
/* visited link */
a:visited {
    color: grey;
    background-color:white;
}
 
/* mouse over link */
a:hover {
    color: orange;
    background-color:grey;
}
 
/* selected link */
a:active {
    color: red;
    background-color:grey;
}

If you now add the above code to your stylesheet and reload the page you should now have styles being applied to every state of the link …

Small Exercise: How could we remove the default underline from all four states of the link?

Download these files if the workshop commences here: CSSLayoutWorkshop

Exercise:: Practice on what was learnt so far:

  • Create a correct and standard-compliant HTML 4.01 basic document structure. Inside the title element, place the text Exercise: Links.
  • Place an h1 element at the top of the page, just underneath the opening body tag. Place the text “My Favorite webpages” in the h1 element.
  • Place the following text after the h1 element. You may line break by using either “p” elements or “br” tags:
    For news I watch CBC.
    I spend alot of time on Wikipedia.
    I am learning HTML with w3 schools.
    I purchase a lot of items from Amazon.
    Everyone should donate money to the SPCA.
  • Create links to the following addresses. Be careful to select the text indicated as the link text—the part of the text that the user can click to activate the link.
    CBC: http://www.cbc.ca
    wikipedia: http://www.wikipedia.org
    w3 schools: http://www.w3schools.com/
    Amazon: http://www.amazon.ca
    SPCA: http://www.spca.com
  • Create a style element with appropriate attributes in the head section of the document.
  • Using the CSS styling, adjust the appearance of the links so that they always appear dark gray. They become underlined only when the user hovers their mouse over the link text.
  • Below the link SPCA, add text that says “See my other page…” Place this text as a p element.
  • Create a new HTML page using the correct document structure for HTML 4.01. In the page, place the text “This is my other page. Go back to my first page” in the document body using p tags.
  • Use “Go back to my first page” as link text to create a link back to the first page you created.
  • On the original page you created, create a link to the new page you created using “See my other page…” as link text.

Solution to the exercise is available here:

CSS LAYOUT

So – we have done a little work in controlling background-color, text color+ fonts – and we have learnt how to apply a style to a specific HTML element.However we have not touched on the real power of css – building a layout for our pages using CSS…

THE BOX MODEL & POSITIONING

One principle necessary to fully understand HTML and CSS is the box model: which states that every element on a page is a rectangular box, and may include margins, padding, and borders.

Having a general understanding of the box model is crucial as websites are primarily built around it. Additionally, knowing how to position elements on a page to build a layout is equally important. There are a few different ways to position elements, each of which depend on the content and circumstance…

Box Sizing:
We know that every element on a page, block or inline level, is a rectangular box.
These boxes can come in different sizes and may have margins, padding, and borders to alter their size. The formation of all of these properties together is referred to as the box model. Let’s take a look at the box model, along with these CSS properties to better understand what we are working with:

The box starts with the height and width of an element, which may be determined by the type of element, the contents of the element, or by specified height and width properties.

The height and width is then followed by the padding and border.

The margin follows the border, however it is not technically included within the actual size of the box.

In summary: the Box Model works like this: in the middle you have the content area (let’s say some text), surrounding that you have the padding, surrounding that you have the border and surrounding that you have the margin.

Let’s apply the box model to our “div” elements in our index2.html page, by writing the following in our style.css:

1
2
3
4
5
6
7
8
div {
    background-color: #ccc;
    border: 6px solid #ff0000;
    height: 150px;
    margin: 20px;
    padding: 20px;
    width: 400px;
    }

What do we notice when we run the page?

  • All div tags in the page now have the “div” style applied to them, resulting in the div elements now being visible containers.
  • The paragraph (p) elements remain the same as before – as there is no specific style being applied.
  • The style definitions applied to the body tag will affect ALL elements contained within the body tag UNLESS we redefine a specific style property for a given contained element. For example the background-color of all the divs are now grey because we redefined the background- color property style definition for the div element.

A small example: If we look at the style.css we see that we have defined the font size for text within the body element to be 14px. Given that ALL other elements are contained within the body element – by default then ALL text will be 14px. But – what if we want to redefine the font size property for all text WITHIN a div tag?

Solution: we redefine the font-size property within the div selector in the style.css file:
The following code will redefine the font size and color when you add it to the style definition of the div:

1
2
 font-size: 10px; 
  color: red;

When you now run index2.html – you should now notice that ALL elements within a div tag will have the new font styles applied. This example demonstrates that all elements by default will INHERIT the style definitions of their PARENT container.

If we look at our index2.html page – we see that within each of the div elements we have paragraph elements. Let us see what happens if we add a style definition specifically for the paragraph element in our style.css file:

1
2
3
4
5
6
7
8
9
10
 p{
    background-color: orange;
    border: 2px solid #ff0000;
    height: 50px;
    margin: 5px;
    padding: 5px;
    width: 400px;
    font-size: 12px; 
    color: black;
    }

If you save the css file and reload the index2.html file – you should now see that each paragraph is now also a visible container WITHIN the div elements as well as the ones OUTSIDE of the div elements. Also note that since all of the text within the div elements are actually within the paragraph elements – the text now uses the paragraph style definition.

If we put text within a div element BUT not within a paragraph element – then it should have the default style from the div element. Lets verify this:
Add the following to the index2. html page – place directly under the h1 tag:

1
2
3
4
 <div>
       Just some text within a div tag ...
        <p>Paragraph (Block level) nested in a div</p>
    </div>

Now save and reload the index2.html page.

Both the p and the div elements are BLOCK LEVEL elements. In our css we have EXPLICITLY defined a height + width for both of these elements. If we had not defined these explicitly:

  • the default height of the element is determined by its content. An element will expand and contract vertically as necessary to accommodate its content.
  • The default width of an element depends on its display type. Block level elements have a default width of 100%, consuming the entire horizontal space available.

Remove the width + height properties from the div style definition and reload the index2.html page …

In contrast to BLOCK LEVEL elements: Inline elements expand and contract horizontally to occupy their content then stop. Inline level elements cannot have a fixed size: the width property, as with the height property, is only relevant to block level elements.

Lets add a style definition for the span tag:

1
2
3
4
5
6
7
8
9
span{
    background-color: green;
    border: 2px solid #ff0000;
    margin: 5px;
    padding: 5px;
    font-size: 18px; 
    color: black;
 
   }

Add to your style.css file – save and reload the index2.html page. Now try and add a width/ height property to the span element – Note that it has no effect whatsoever….

To break down the total width of an element, including the box model, use the formula:
margin-right + border-right + padding-right + width + padding-left + border-left + margin-left

In comparison, the total height of an element, including the box model, can be found using the formula:
margin-top + border-top + padding-top + height + padding-bottom + border-bottom + margin-bottom.

See the figure to visualize this:

box-model(http://learn.shayhowe.com)

The margin property: space around exterior of elements – allows us to set the length of space surrounding an element. Margins fall outside of any border and are completely transparent. Margins can be used to help position elements within a particular place on a page or to simply provide breathing room, keeping all other elements a safe distance away.

The padding property: space around inside of box is very similar to that of the margin property, however it falls within any elements border.Paddings will also inherit any backgrounds of an element. Padding is used to provide spacing within an element, not for positioning an element like the margin property.

When using either the padding or margin properties: you may define one value for all 4 sides or you may choose to be more specific and define a value for each side: The following example sets a unique value for each side of the margin (in order :top, right, bottom, and left)

1
div {margin: 10px 20px 0 15px;}

Or you can specify a specific property by for example:

1
div {margin-top: 10px;padding-left: 6px;}

Borders fall between the padding and margin and provide an outline around an element. Every border needs three values: a width, style, and color. Shorthand values fall in the order of width, style and color. Longhand, these three values can be broken up into the border-width, border-style, and border-color properties.

So far we have specified in our style sheet a style solely for HTML selectors – those that represent an HTML tag (div, span, p …).You can also define your own selectors in the form of class and ID selectors. The benefit of this is that you can have the same HTML element, but present it differently depending on its class or ID.
So the CSS might look something like:

1
2
#top {background-color: #ff0000; padding: 0px;}
.intro {color: red; font-weight: bold;}

Then, the HTML will refer to the CSS by using the attributes id and class. It could look something like this:

1
2
3
4
5
<div id="top">
<h1>This heading is inside the div with id "top"</h1>
<p class="intro">Is this paragraph different?</p>
<p class="intro">And this one?</p>
</div>

Place the above example into your html & css pages respectively and verify the changes … Note::: Because we also created a style for the corresponding HTML selectors, we will still use any of those style definitions as long as they are not redefined in the more specific class or id definitions.

The difference between an ID and a class is that an ID can be used to identify one element, whereas a class can be used to identify more than one.

Exercise using the Box Model:
Create a webpage that contains three content boxes (divs). Set the following attributes in each of the boxes as follows:

  • box 1: padding: 10px, border: 15px; green; solid margin:10px, content color:any
  • box 2: padding: 5px, border: 15px; teal; groove margin:10px, content color:any
  • box 3: padding: 2px, border: 2px; aqua; dotted margin:10px, content color:any

Solution to the exercise available here:

Inline vs. Block Level Elements continued
Lets start with a new HTML document. Create two divisions. Assign id values as div1 and div2. Enclose some text inside a paragraph tag in one of the divisions and some text portions in the same division inside a span tag. Add some styling to the 2 divs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<html>
<head>
	<title>Inline div vs. Block divs</title>
	<style type="text/css">
#div1, #div2
{
	font-family: arial;
	font-size: .8em;
	width: 400px;
	border:1px solid black;
}
</style>
</head>
<body>
<div id="div1">
Start Div 1 Cras euismod nunc non turpis
	accumsan eu dictum nibh adipiscing. Etiam
	et hendrerit massa. Morbi pretium, magna
	sed consectetur hendrerit, dolor dolor
	sagittis nibh, id ullamcorper leo dui sit
	amet diam. Sed in urna sapien, eget tempus
	elit. Fusce sed mattis urna. Quisque ac
	ipsum sapien, quis aliquet erat.
</div>
<div id="div2">
Start div 2 Cras euismod nunc non turpis
	accumsan eu dictum nibh <span>SPAN starts... adipiscing.
	Etiam et hendrerit massa. Morbi pretium, </
	span>magna sed consectetur hendrerit, dolor
	dolor sagittis nibh, <p>id ullamcorper leo
	dui sit amet diam. Sed in urna sapien, eget
	tempus elit. Fusce sed mattis urna. Quisque
	ac ipsum sapien, quis aliquet erat.</p>
</div>
</body>
</html>

When you run the page in the browser – we can see that the division tags and paragraph tags are by default block level elements. You can change this default positioning (i.e. to align a division tag horizontally) by setting an inline attribute in the corresponding styles.
To introduce these inline attributes, we can use the attribute modifier display: inline. Apply this to the #div1 selector:

1
#div1{display:inline;}

Now, when you run the page you will see that the first division is now being treated as an inline element…

Consequently, we can also change an inline element (i.e. a span element) to be treated as a block level element by specifying: display: block. Apply this to the span tag:

1
span{display:block;}

We have already gone over the width and height attributes for a block level element. There is one other attribute that I would like to mention here: the overflow attribute :
If the set height does not accommodate the whole text content, the excess or text overflow can be manipulated with the “overflow” option. Some options for overflow are: auto, scroll, visible and hidden.
Lets briefly test this attribute on the division that has the id div_2:

1
#div2{height: 50px;overflow:hidden;}

We have specified a height for this element -and an overflow property of “hidden”. Therefore when you run the page – you will see that the text that does not fit within the specified height is hidden .

If you change the overflow property to scroll, scroll bars will appear, allowing the user to scroll through the rest of the text.

If you use the auto property: the overflow works in such a way that it only places a scroll bar whenever needed.

The visible property makes the content visible including its overflow into other blocks.

Floating Elements:
Outlining elements within the box model is only half the story to coding a page layout… The other half involves knowing how to properly align all of the different elements on the page:

The first way to position elements along side one another is to use the float property:

We can look to print design to understand the origins of the float property:
In a print layout, images may be set onto the page such that text wraps around them as needed. Here is an example of that.
print-layout
In page layout programs, the boxes that hold the text can be told to honor the text wrap, or to ignore it. Ignoring the text wrap will allow the words to flow right over the image like it wasn’t even there. This is the difference between that image being part of the flow of the page (or not). Web design is very similar.
web-text-wrap

In web design, page elements with the float property applied to them are just like the images in the print layout where the text flows around them. Floated elements remain a part of the default flow of the web page.
In order to illustrate this lets build a small example:

  1. Download the following images: floatImages and place them in the images folder in your practice folder.
  2. Create a new html page in your text editor and save it as floatEx.html in the practice folder.
  3. First: lets add the html elements: basically we will have two paragraphs and two images contained within a div tag – save the following into your new file:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    <!DOCTYPE html>
    	<head>
    		<title> Float Example </title>
     
    	</head>
     
    	<body>
     
    <div>
    <p>
    <img src="floatImages/t.jpg" width ="100px" height ="100px"/>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>
    <img src="floatImages/t2.jpg" width ="100px" height ="100px"/>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
    </div>
    </body>
    </html>
  4. Now: if you view the page in your browser – You should be able to see your images and the text…

  5. Next we want to apply some styling to the page: i.e we will give our div tag a width, height and background color… So copy the following and reload the page:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
    <style>
     
       div
       {
        /* This is a comment in css */
        background: #6699FF;
        height: 700px;
        margin: 20px;
        padding: 20px;
        width: 600px;
       }
      img
      {
        margin: 10px;
      }
     
        </style>
  6. Ok – well this is already looking better – however the text is not wrapping around the images – rather we have an image and only on the line where the image ends – does the text begin. However – by using the float property applied to the image tag – we can gave the text wrap around the image: So add the following in the img style definition:

    1
    
    float:left;
  7. Now if you reload the page – hey! we have text wrapping! – How do you think we could put the images on the right instead of the left?

There are a few important things to note when floating elements:

  1. When floating an element it is going to float all the way to the edge of its parent container.
  2. If there isn’t a parent element it will float all the way to the edge of the page.

    Small example: remove the div tag in the float example html page — how does the layout change?
  3. Additionally, when floating an element other elements will begin to line up around it within the natural flow of the page.
  4. There are four valid values for the float property. Left and Right float elements those directions respectively. None (the default) ensures the element will not float and Inherit which will assume the float value from that element’s parent element.

Clearing the Float Property
Float’s “sister” property is called clear. An element that has the clear property set on it will not move up adjacent to the float like the float desires, but will move itself down past the float. Again perhaps an example would be needed here:

  1. Make a new html page: and now we are going to use the HTML 5 tags: article, aside and footer – our goal is to create a standard layout:
    left: the article , right: the aside column, and underneath a footer:
    Start by copying the following:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    
    <!DOCTYPE html>
    <html>
    	<head>
    		<title> Float Example with clear </title>
    		<style>
     
       article{
       background: #6699FF;
       width: 80%;
       height:500px;
      }
     
        aside{
        background: #33CC33;
        width: 20%;
        height:300px;
       }
        footer{
        background: #FF3300;
        width: 100%;
        height: 100px;
       }
     
        </style>
    	</head>
     
    <body>
        <article> Main Text </article>
        <aside> Aside</aside>
        <footer> foot </footer>
     
    </body>
    </html>
  2. At this point we have some elements::: but we need to use the float property to make sure our article and aside elements are lining up as we want them to: so add the float:left to the article style, and float:right to the aside style.
  3. Now we would assume that the “footer” element would be at the bottom when we reload the page? – Nope:: why?

    In the above example, the aside element is floated to the right and is shorter than the article area. The footer then is required to jump up into that available space as is required by the float. To fix this problem, the footer can be cleared to ensure it stays beneath both floated columns:
    Put the following into the style for the footer:

    1
    
    clear:both;
  4. And now if we reload the page – everything has lined up correctly!
    Clear has four valid values as well. Both is most commonly used, which clears floats coming from either direction.
    Left and Right can be used to only clear the float from one direction respectively.
    None is the default, which is typically unnecessary unless removing a clear value from a cascade.

Lets do a last example to demonstrate the clear property in another context:

  1. As usual start with a new html page. Then copy the following:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    
    <!DOCTYPE html>
    <html>
    	<head>
    		<title> Clear Float Right Example </title>
    	</head>
     
    	<body>
     
     
    <p>
    <img src="floatImages/t.jpg" width ="100px" height ="100px"/>
    <img src="floatImages/t2.jpg" width ="100px" height ="100px"/>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
    </body>
    </html>
  2. At this point we would like to have both images on the right and the text wrapping around them … so we can use for demonstration purposes an inline style definition to both img elements: Place the following within BOTH img tags:

    1
    
    style ="float:right; margin:2px;"
  3. Now: when you load the page you should see both images along the right …

  4. But now we want to try and have the images underneath eachother but both on the right side:
    So we can apply the clear property to the second image and AFTER apply the float. REPLACE the following on the SECOND image tag (remove the first style definition).

    1
    
    style ="clear:right; float:right;margin:2px;"
  5. Now when you reload the page: the first image is on the right, then we clear the float for the second image – and then reapply the float:right property – which has the effect of pushing it to the absolute right hand side.


    Question: – what would happen if we DID not reapply the float property to the second image?

Using the float property is really useful – and therefore we will design a more complex layout – using the float property. We will also see a more generalized approach for clearing the float property:
Lets start with a standard web page:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<DOCTYPE HTML>
	<HTML>
		<head>
			<meta charset="utf-8">
			<title></title>
 
			<link href="start.css" rel="stylesheet" type="text/css">
 
		</head>
		<body>
			<header>
				<nav>
 
				<ul>
					<li> <a href="#">Menu Item 1</a></li>
 
					<li> <a href="#">Menu Item 2</a></li>
					<li> <a href="#">Menu Item 3</a></li>
					<li> <a href="#">Menu Item 4</a></li>
                                   </ul>
				</nav>
			</header>
			<main>
				<div class="box-set">
				<figure class="box">Box 1</figure>
				<figure class="box">Box 2</figure>
				<figure class="box">Box 3</figure>
			</div>
			</main>
			<footer>
			</footer>
		</body>
		<HMTL>

And the style sheet: call it start.css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/* STEP 1: the best way to reset margins for all elements is to use the css asterisk rule.
 * start with this and then set the margins and paddings of sub containers accordingly*/
* {
   margin: 0px;
   padding: 0px;
}
header
{
	/* light blue */
	background:#4cdfff;
}
/* if not specified a division tag will take up 100% of width */
nav
{
	/* darker-blue */
	background:#339cb5;
}
 
 
main
{
	background:#226878;
	/*text color */
	color: white;
}
 
.box-set {
  background:#a2a399;
  /* take up 80% width of parent container */
  width:80%;
}
 
.box {
  background:#a32318;
  padding: 20px 0;
  margin:2%;
  width: 25%;
}

Now if you run the page – you should see quite a few colored boxes… Lets look at the style sheet briefly: Everything should be familiar except for the first rule: is called the asterisk rule . This rule will select ALL elements at will apply the specified style accordingly.
OK – lets say we want our boxes to align horizontally: so within the “.box” style we specify float:left;. Now run the page… What happened to our background parent boxes? -They seem to have disappeared. Explanation: The content on the page will respect the size and placement of the floated children elements, but these floated elements no longer impact the outer edges of the parent container. In this event the parent element loses context of exactly what it contains and collapses, thus giving the parent element a height of 0 and ignoring various other properties…. There are various solutions to these problems so lets go through them one by one:

Solution 1:
One way to force containing these floats would be to place an empty element just before the parent element’s closing tag (in this the parent is identified by “box-set”, of which would need to include the style declaration clear: both;.
HOWEVER:: this is a quick fix technique – and we don’t really want empty divs – whose purpose is just to clear the float property and restore the default flow – is semantically incorrect…

  • In the HTML page add a new div tag (empty) and give it a class name “mClear”. Place it under the last box element (within the box-set div)
    1
    
    <div class="mClear"></div>
  • Define a style for “mClear”:
    1
    
    .mClear{clear:both;}

Solution 2:
THE OVERFLOW TECHNIQUE
One technique for containing floats within a parent element is to use the “CSS overflow property”. Setting the overflow property value to “auto” within the parent element will contain the floats, resulting in an actual height for the parent element, thus including a gray background in our example:

  • Remove the mClass div from the html page
  • Now add the property overflow:auto; to the box-set style.

Using the overflow technique does come with a few drawbacks.
For example, when adding styles or moving nested elements that span outside of the parent, like when trying to implement box shadows and dropdown menus.
WHERE IT WILL BREAK :::
In the demonstration below, you can see how the box shadow is being cut off wherever it lies outside the parent element. Additionally, the second box is cropped outside of the parent element.
If overflow is set to auto we get scroll bars and if is set to hidden – it just crops…
Overwrite your start.css with the following style definitions to see our issue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/* STEP 1: the best way to reset margins for all elements is to use the css asterisk rule.
 * start with this and then set the margins and paddings of sub containers accordingly*/
* {
   margin: 0px;
   padding: 0px;
}
header
{
	/* light blue */
	background:#4cdfff;
}
/* if not specified a division tag will take up 100% of width */
nav
{
	/* darker-blue */
	background:#339cb5;
}
 
 
main
{
	background:#226878;
	/*text color */
	color: white;
}
 
.box-set {
  background:#a2a399;
  /* take up 80% width of parent container */
  width:80%;
  /*SOLUTION:: hidden - no scroll bars, auto: with scroll bars if needed*/
  overflow:auto;
}
 
.box {
   box-shadow: 0 15px 30px #ff0000;
 
  background:#a32318;
  padding: 20px 0;
  margin:2%;
  width: 25%;
  float:left;
 
 
}
.box:nth-child(2) {
  position: relative;
  top: 20px;
}

Note::: We have a new style rule – which uses the position attribute (will come to in a moment…).
So how to really fix the issue?

Solution 3:
Depending on the context of the floated elements a better technique to contain floats may be the clearfix technique. The clearfix technique is a bit more complex but does have better support as compared to the overflow technique.::

The clearfix technique is based off using the :before and :after pseudo-elements on the parent element. Using these pseudo-elements, we can create hidden elements above and below the parent containing the floats.
The :before pseudo-element is used to prevent the top margin of child elements from collapsing by creating an anonymous table-cell element using the display: table; declaration.

The :after pseudo-element is used to prevent the bottom margin of child elements from collapsing, as well as to clear the nested floats.

**It is worth noting only one :before and one :after pseudo-element are allowed per element, for the time being.
When trying to use the clearfix technique with other :before and :after pseudo-element content you may not achieve the desired outcome…
Overwrite your css file with the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* STEP 1: the best way to reset margins for all elements is to use the css asterisk rule.
 * start with this and then set the margins and paddings of sub containers accordingly*/
* {
   margin: 0px;
   padding: 0px;
}
header
{
	/* light blue */
	background:#4cdfff;
}
/* if not specified a division tag will take up 100% of width */
nav
{
	/* darker-blue */
	background:#339cb5;
}
 
 
main
{
	background:#226878;
	/*text color */
	color: white;
}
 
.box-set {
  background:#a2a399;
  /* take up 80% width of parent container */
  width:80%;
}
/* create a "psedo element before and after the box set ... "*/
.box-set:before,
.box-set:after {
  content: "";
  display: table;
}
.box-set:after {
  clear: both;
}
 
.box {
   box-shadow: 0 15px 30px #ff0000;
 
  background:#a32318;
  padding: 20px 0;
  margin:2%;
  width: 25%;
  float:left;
 
 
}
.box:nth-child(2) {
  position: relative;
  top: 20px;
}

So now if we run the page – we seem to have some nice looking boxes!
Creating a CSS Navigation Bar:
One of the most complicated aspects of HTML is creating a navigation bar… so instead of relying on bitmaps and dreamweaver – lets look into creating a simple navigation bar styled with css. The page that we have been currently working with has a simple navigation bar – but it is not styled… It is comprised of an unordered list of items within the “nav” HTML element. Right now the bulleted list looks as if there are no bullets – however do not be fooled! If, in the asterisk rule you change the margin property to i.e. 5 px and run the page you will see that in fact there are bullets!

So – to get rid of them: we define a rule in our style sheet for the ul selector:

1
ul{list-style-type:none;}

Next step: We want to eliminate the underline of the links and set the color of the links to light blue. To do that, change the text-decoration attribute to none:

1
li a:link, li a:visited{text-decoration: none;color:#77c8ff;}

Next: since we are looking to have a horizontal navigation bar – lets float all our list items to be left::

1
li{float: left;}

And now lets apply the overflow method – to make sure that the other elements on the page are not affected::
Add the following to the ul rule.

1
overflow: hidden;

OK – its already looking like something resembling a nav bar….but we still have some finessing::
We want to apply a background box when we hover over the link- so we choose to add a background color to the li tag when we hover over it … note you could at this point instead apply this to the a tag – but note the difference:::

1
li:hover {background: #ff0000;}

Then we can also change the text color when we hover over the link:

1
li:hover a {color: #fff;}

And finally – if we want the a tag to behave like a block element: makes the whole link area clickable (not just the text), and it allows us to specify the width. Since block elements take up the full width available, they cannot float next to each other. We specify the width of the links to 100px.

1
2
/* for the a tag */
 a {display: block; width:100px;color: #757575; text-decoration: none;}

And there you have it – your basic navigation bar all styled with css.

Positioning Elements
The position property is used to define whether a box is absolute, relative, static or fixed.

  • static is the default value and renders a box in the normal order of things, as they appear in the HTML.
  • relative is much like static but the box can be offset from its original position with the properties top, right, bottom and left.
  • absolute pulls a box out of the normal flow of the HTML and delivers it to a world all of its own. In this world, the absolute box can be placed anywhere on the page using top, right, bottom and left.
  • fixed behaves like absolute, but it will absolutely position a box in reference to the browser window as opposed to the web page, so fixed boxes should stay exactly where they are on the screen even when the page is scrolled.

Normal flow of a document refers to how the elements by default “stack”one on top of the other in the order in which they appear in the markup. – So when we apply the “position” property to an element: we are redefining the “flow”.
Lets start with a brand new html page (save it as whatever you like):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html>
	<head>
		<title> Example Sections Positioning </title>
		<link rel="stylesheet" href="posstyle.css">
	</head>
	<body>
		<div id = "box_1">
			<p> box 1  in div </p>
		</div>	
		<div id = "box_2">
			<p> box 2 in div </p>
		</div>	
		<div id = "box_3">
			<p> box 3 in div </p>
		</div>	
	</body>
</html>

Now this file also specifies a link to “posstyle.css”, so create a new style file and add the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#box_1 { 
	position: static;
	width: 200px;
	height: 200px;
	background: #ee3e64;
}
 
#box_2 { 
	position: static;
	width: 200px;
	height: 200px;
	background: #44accf;
}
 
#box_3 { 
position: static;
width: 200px;
height: 200px;
background: #b7d84b;
}

Note:: you will see that in the html file for every div element we have allocated a unique “id” attribute (box_1, box_2, box_3). This allows us to do something clever in our style sheet: instead of defining a style for a div element which would then be applied to every div element in the page – we have defined a style for every “id” attribute. Therefore, the style named “box_3” will be only applied to elements on the HTML page whose id attribute has the value “box_3”. This is a clever mechanism to allow for specific styles to be applied to specific elements (even when they are the same HTML element type).

When you load the page – the elements are displayed as expected: stacked – since they are all given the default value of “static”.

If we change the position of box_2 to “relative”: what happens? nothing – as expected.

But – when a position is declared relative: we can offset the box from its original position with the properties top, right, bottom and left.

  • top: an offset starting from top
  • bottom: an offset starting from the bottom (0px = bottom)
  • left: an offset starting from the left
  • right: an offset starting from the right (0px = all the way to the right)

Add top:20px; left:20px; to the style of box_2.

What happens? – box_2 is now offset by 20px from the top and from the left of the parent container (the document). However – box-1 and box 3 have not changed!

Being that we are using relative positioning: box_2 will be moved relatively to its original position (from where it was ORIGINALLY placed in the normal flow of the document).

What happens if we leave the offsets for box_2 and change the position property to absolute? See the difference? Now we have allocated absolute positioning and box_2 will be placed at 20px from the top of the document and 20px from the left…

Exercise:

  • Add a box_4 to your html page and a corresponding style.
  • Using absolute positioning (top, left, right, bottom) – try to have each box take up either the Top-Left, Bottom-Left, Top-Right, Bottom-Right Corners.

Now we can using positioning easily make a 2 column layout.
Comment out all code/markup relating to box_3 and box_4.
Now overwrite the following styles for box_1 and box_2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#box_1 { 
	position: absolute;
	top:0px;
	left:0px;
	width:20%;
	height:100%;
	background: #ee3e64;
}
 
#box_2 { 
	position: absolute;
	top:0px;
	right:0px;
	width: 80%;
	height: 100%;
	background: #44accf;
}

Why does this work?
Exercise:

  • Extend the 2 column layout to a 3 column layout – solution:posstyleFor3Col

A final exercise:

With 4 boxes in each corner place a smaller box in the center of each one (remove the p tags from each box) – using only one more style definition.

This exercise will show that – when we have a child container – even with absolute positioning, the top, left, bottom or right coordinates specified in the child container will be relative to the parent container. See solution: posstyle
There are alot of CSS properties that we did not go over: ie z-index for layering elements, the display property, the visibility property – however, what we have covered today should give you a good basis – and hopefully if you look for any more advanced or other CSS properties online then – you should have an idea how to use them from the examples.

If we have time why not go to w3schools and try out some examples?