Click here to Skip to main content
15,880,469 members
Articles / Web Development / HTML5

Beginner's Guide to HTML5/CSS3 - Part 4 of 12

Rate me:
Please Sign up or sign in to vote.
5.00/5 (7 votes)
7 Apr 2014CPOL13 min read 19.8K   321   15   3
Laying Out Your First Web Page

List of Articles in Series

  1. Writing your First Code
  2. Building on the Basics
  3. Styling Your First Web Page
  4. Laying Out Your First Web Page

Introduction

I've already mentioned that CSS is our tool to design the layout of our HTML document. In this part you will learn how to do layout with CSS...

Using the code

The code sample in this part continues and extends the one from the previous part. I beg you to take it and do as there, make the additions as we learn new things.

Box Model

Box model is the buzz word that covers the way of browser to compute the space taken by every single tag in the HTML document. To understand it is crucial to your ability to create fantastic web pages (to Microsoft it took over 15 years to understand it, so don't panic if you have to read it more than once).

Build-up of Single Tag

When browser is about to render you HTML document it creates a rectangular area (box - hence the name) for every and each of the tags in it.

Image 1

The above image shows the building parts of the box for a single tag. The content part is the actual tag, its size either computed by the browser or you may set it using width and height properties. For the other parts let see some explanation...

Definition

Explanation

padding-top
padding-right
padding-bottom
padding-left

Clears an area between the content and its border. There is an attribute for every direction, or you can use the padding shorthand attribute to set them together...
The default value is 0 (no padding), but if there is it get the same background as the content.

border-top-width
border-right-width
border-bottom-width
border-left-width

Sets the width of the border around the content (and the padding, if any).
The border-width shorthand attribute can be used to set it in one step...
You can set it to any numerical value, or select one of the keywords: medium (default), thin or thick.

border-top-style
border-right-style
border-bottom-style
border-left-style

Sets the style of the border around the content (and the padding, if any).
The border-style shorthand attribute can be used to set it in one step...
The possible values are:
none (default), dotted, dashed, solid, double, groove, ridge, inset and outset.

border-top-color
border-right-color
border-bottom-color
border-left-color

Sets the color of the border around the content (and the padding, if any).
The border-color shorthand attribute can be used to set it in one step...
Any color value we learn about in the previous part (background-color) is acceptable...

margin-top
margin-right
margin-bottom
margin-left

Clears an area around the tag - outside the border.
The margin shorthand attribute can be used to set them all together.
The area defined by the margin is completely transparent.

It is extremely important that you understand, that when (and if) you setting the width and height of a tag (or examining the computed values the browser assigned), those values are for the content only. All other attributes we mentioned are adding to that width and height, so if you are about to compute the exact size of any element you have to add padding, border and margin as well!

Build-up of Page

Now, when the rendering engine of a browser builds a page out of the boxes of the tags, there are some rules to follow. To explain that rules, first let me introduce you two more ideas, used to group tags. There are tags that can play nicely while in line with other tags - they called inline tags. These tags are allow to other tags to be on their left and right, but you can't set their width and height, not top and bottom margin and padding. All those attributes are computed according to the line the tag sits in...

On the other hand there are tags that have to sit alone in a separated block - they called block tags. You can set all the above attributes on them, but there will be a break before and after them.

Image 2

Derived from these: an inline tag can not contain block tags, but a block tag can contain both inline and block tags... For instance the article level semantic elements you saw in the second part are defined as block, on the other hand the text level semantic elements - from the same part - are inline (except blockquote).

Now when the browser builds the page, by putting those boxes representing the tags according inline-block rules, it also merges margins according to the rule of collapsing margins. Collapsing margins is about to merge vertical margins into one when certain rules are apply. Before I show you those certain rules, please notice something: collapsing margins are about top and bottom margins only so is only about block level tags!!!

The margins that can collapse into one are:

  • Bottom margin of a block tag with top margin of the next block tag in the flow
  • Top margin of a block tag with top margin of its first child
  • Bottom margin of a block tag with bottom margin of its last child

Let see it in action. See the HTML and CSS source...

HTML
<!DOCTYPE html>
<html>
<head>
    <title>Boxmodel</title>
    <link href="boxmodel.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <h2>Title</h2>
    <p>First paragrpah</p>
</body>
</html>

h2 {
    margin: 20px 10px;
    background-color: gray;
}

p {
    margin: 10px;
    background-color: aqua;
}

Now you can see that the H2 heading has a 20 pixel high bottom margin and the paragraph has a 10 pixel high top margin. Without the collapsing margin rules that should give us 30 pixel high clear area between the two element, but according that rule we get only a 20 pixel.

As I told, it's is extremely important to understand these concepts, as when designing the layout of your page these attributes and rules must take into consideration!

How to Measure Your Page

You already saw that I used some kind of units when assigned numeric values to those attributes that may have it. In the previous part I used em to size tags and just above I used px to set margin. Before we move on I want to show you the possible measurement units CSS can accept...

Length units

Unit

Explanation

cm

Centimeter.

mm

Millimeter.

in

Inches.

px

Physical pixel of the display device.

pt

Point. 1 point is equal to 1/72nd of 1 inch.

pc

Pica. 1 pica is equal to 12 points.

Font based units

These units are computed based on the current font used in your HTML document

Unit

Explanation

em

Height of the current font.

ch

Height of the 0 (zero) char in the current font.

rem

Height of the font assigned to the root of the HTML document.

Viewport based units

In the word of mobile, we no more using screen as our display media, but view-port. These units are based on the size of that view-port...

Unit

Explanation

vw

1 % of the view-port width.

vh

1 % of the view-port height.

vmin

1 % of the view-port smaller dimension.

vmax

1 % of the view-port larger dimension.

Set the Content Box

We already saw the difference between inline and block elements when height and width involved. Now I want to show all the attributes can be used to set the dimension of a piece of content... Our options are min-height, max-height, height and min-width, max-width, width. These attributes are allow you to control the dimension of one tag. The min-, max- attributes are used to set a range, where height and width are used to set a direct value. If more then one of these attributes declared max- overrides direct, and min- overrides max-.

These attribute can accept the auto keyword (default), a numeric value or percentage. For instance, the 50% value in the next sample tells the browser make the image half of the computed width and half of the computed height...

HTML
<img src="picture.png" alr="picture" width="50%" height="50%">

Back to The Blog

I want now to pick up our sample from the point we left it and use our new knowledge to add more beauty... First of all I want you to notice the white gap around the whole content. That is the default margin added by your browser. Now, in the first phase I want to do these things:

  • Remove page margin.
  • Add some space between content and border in the header (padding)

Note: I will not post a image for every step anymore - at this point you probably will be able to see that yourself, so don't just read the article, but work alongside with it!

For the first step update you CSS file to look like this:

CSS
body {
    font-family: serif;
    font-size: 1.2em;
    margin: 0;
}

Notice that we set margin to 0 on the body element, that is our document. You will see that the mentioned white gap is gone, however the text and image now stacked to the edge of the browsers window...very unpleasant! So add some padding around the content that looks bad...

CSS
article {
    background-color: #fff;
    padding: 16px;
    margin: 16px;
}

h1 {
    background-image: url("green.jpg");
    background-attachment: fixed;
    line-height: 4em;
    text-transform: uppercase;
    font-family: fantasy;
    font-size: 3em;
    font-weight: 900;
    padding-left: 32px;
}

header > aside {
    letter-spacing: +0.15em;
    white-space: nowrap;
    font-family: NothingYouCouldDo;
    padding-left: 16px;
}

footer p {
    text-align: center;
    letter-spacing: +0.05em;
    font-family: monospace;
    padding-top: 4px;
    padding-bottom: 4px;
}

Take your time and play with those paddings, to get the best look for you.

Now for last change in this section I want to re-size the picture of me, it's a bit too large... For that we add a new rule to our CSS:

CSS
header > img {
    width: 50px;
    height: 50px;
}

Now for move on with our sample I want to extend it by adding a menu bar and a side navigation to move between the articles. For that I added two unordered lists, one inside the header, and one just before the articles...

HTML
<header>
    <img src="me.jpg" alt="me" width="150" height="150">
    <aside>Kornfeld Eliyahu Peter</aside>
    <h1>Me Blog</h1>
    <nav>
        <ul>
            <li>Home</li>
            <li>About</li>
        </ul>
    </nav>
</header>
<section class="side-menu">
    <ul>
        <li>Fusce vel dolor sollicitudin</li>
        <li>Fusce aliquet augue</li>
    </ul>
</section>
<section class="main">
    [article content as before]
</section>

Now that addition is looks a bit awkward, but as we go on you will see how to fix that by what we will learn, so be patient...

The Ingredients of CSS Layout

The Display Attribute

You already learned, that every HTML tag has its default display mode - inline or block, fortunately that mode can be changed using the display attribute. The most common values are inline, block and none. As you may expect none will remove the entire tag from the rendering process.

Move Your Tag Around

When browser is rendering your HTML document, the position (top, left, right, bottom) of any tag is computed by the rendering engine and the computed box are placed one after the other according the rules of the box model. I believe it not surprises you, that this also can be changed. Basically changing the clipping box (top, left, right, bottom) isn't enough, you also have to set the position attribute, that tells the rendering engine how to interpret the values for the clipping box.

Position value

Explanation

static

This is the default value. It means that the rendering engine will compute the position and setting the clipping box has no effect whatsoever.

fixed

The clipping box defines a fixed position, that relative to the browsers window. The tag will not move even the window scrolls.

relative

The values of the clipping box are relative to the normal (computed) position.

absolute

The clipping box is interpreted relatively to the tags' first non static parent. If there is no such a parent the root (HTML) tag is used.

Tags with absolute and fixed positioning are removed from the normal flow of the rendering, the rest of the content is rendered as those tags were not exists at all. On of the results of that is that absolute and fixed tags can overlap other tags, including other absolute or fixed tags. When there are overlapping tags you can order them (which displays over which) using the z-index attribute. Tags with greater z-index will be displayed in front of tags with smaller z-index. If there is no z-index specified the tag that comes later in the document flow will overlap others.

Float Your Boat

An other nice feature to break the normal flow of the box model is let text float around images (in fact it works for any two block level tag, but the most common usage is add images inside the text flow). To achieve that you have to use the float attribute. The values are left or right, where the direction indicates to which side the floating tag will move, on its other side will wrap the next block level tag after the floating tag. The only problem is that all tags coming after that will wrap themselves around the floating tag (as long as they have space for that). Sometimes this behavior is not acceptable. Fortunately we have an attribute to stop floating - clear. The values for clear attribute are left, right or both, where left stops left side floating, right stops right side floating and both stops all floating.

Image 3

An Example of Flow

Now let use that floating attribute to put the side navigation and the article content side-by-side...

CSS
section.side-menu {
    float: left;
    width: 25%;
}

section.main {
    float: right;
    width: 75%;
}

footer {
    background-color: #b1b1b1;
    clear: both;
}

As you can see we send the side navigation to left and the articles to the right. Also notice the clear attribute that restores the footer to it's normal position.

Using Border Attributes

Now, we already saw some of the border attributes while explaining the box model, no put it in action by adding a nice border around each article. But just before that, let me introduce you the border-radius attribute. This attribute allows you to create a rounded corner for the border, where the numeric value defines the radius of the circle used to draw the rounded corner. So let update our CSS file once more:

CSS
article {
    background-color: #fff;
    padding: 16px;
    margin: 16px;
    border-width: 1px;
    border-style: solid;
    border-color: #f90;
    border-radius: 12px;
}

Style Our Menu

OK, for now we have a nice blog page, but those menus are really not in place. If you remember I already mentioned that those default bullets (or numbers for ordered list) can be changed, let see how...

Position value

Explanation

list-style-type

This attribute defines what signs or numbers used for the list items. Possible values are:
none - no marker
disc - draws a black dot as marker (default)
circle - draws a circle as marker
decimal - decimal number
decimal - leading-zero - decimal number with leading zero
square - draws a square as the marker

These values used to indicate a letter based numbering scheme, each for the language indicated in its name:

armenian, cjk-ideographic, georgian, hebrew, hiragana, hiragana-iroha, katakana, katakana-iroha,
lower-alpha, lower-greek, lower-latin, lower-roman, upper-alpha, upper-latin, upper-roman

list-style-image

Loads a image as the marker. This attribute overrides the type attribute...

Ffirst, let see our top menu bar. I want to remove the marker and make the menu displays in one line.

CSS
nav ul {
    list-style-type: none;
}

nav ul li {
    display: inline;
}

I believe there are no news here, but if you do not understand the display: inline attribute, please scroll up and read again the box model and the layout bit...

For the side navigation I not really need changes but I favor the square marker so let change it:

CSS
section.side-menu ul {
    list-style-type: square;
}

A Bit More of Semantics

We do not used them until now (and to be honest I use them always as last resort) but you have to know two more semantic tags. The only special value of these semantics that they have none. These tags can be use for any none categorized purpose.

There is the DIV tag, that is a block level tag, and the SPAN tag, that is a inline level tag.

Summary

With this part we really got deep into CSS ideas and practice. The only way to keep up is practice and practice and when time left practice more. So download the source and twist it until you understand every bit of it!

License

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


Written By
Software Developer (Senior)
Israel Israel
Born in Hungary, got my first computer at age 12 (C64 with tape and joystick). Also got a book with it about 6502 assembly, that on its back has a motto, said 'Try yourself!'. I believe this is my beginning...

Started to learn - formally - in connection to mathematics an physics, by writing basic and assembly programs demoing theorems and experiments.

After moving to Israel learned two years in college and got a software engineering degree, I still have somewhere...

Since 1997 I do development for living. I used 286 assembly, COBOL, C/C++, Magic, Pascal, Visual Basic, C#, JavaScript, HTML, CSS, PHP, ASP, ASP.NET, C# and some more buzzes.

Since 2005 I have to find spare time after kids go bed, which means can't sleep to much, but much happier this way...

Free tools I've created for you...



Comments and Discussions

 
QuestionNo Part 5 or 6? Pin
Kevin Priddle22-Apr-14 11:09
professionalKevin Priddle22-Apr-14 11:09 
AnswerRe: No Part 5 or 6? Pin
Kornfeld Eliyahu Peter22-Apr-14 11:22
professionalKornfeld Eliyahu Peter22-Apr-14 11:22 
GeneralRe: No Part 5 or 6? Pin
Kevin Priddle24-Apr-14 4:36
professionalKevin Priddle24-Apr-14 4:36 

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.