Click here to Skip to main content
11,641,209 members (62,355 online)
Click here to Skip to main content

Beginning with HTML and CSS - Part 4/12 - Laying Out Your First Web Page

, 6 Apr 2014 CPOL 4.7K 192 14
Rate this:
Please Sign up or sign in to vote.
This article is a startup kit for anyone who is new to HTML and CSS.

Introduction

This article is fourth in the series of 12 articles that will take us through learning HTML5 and CSS3.

This article is intended to introduce the below concepts

Background

The articles related to basics of HTML and CSS will help understanding this article better. Below are the links.

Beginning with HTML and CSS - Part 1/12

Beginner's Guide to HTML5 & CSS3 - Part 2 of 12 (Linking James Jensen's article) ,

Beginning with HTML and CSS - Part 3/12

The Box Model (Border, Outline, Margin, Padding)

"In HTML or generally in Web Design each element is a rectangular box". We all have heard or read this many many times before. What this really means is that the primary goal of a rendering engine (such as a browser) is to determine the properties such as size, color, background, borders and position of these boxes. And what's inside the box is irrelevant.

Just as a refresher, here is how W3C defines Box model: “The CSS box model describes the rectangular boxes that are generated for elements in the document tree and laid out according to the visual formatting model”

If you are wondering how can everything be boxes on a web page, lets do a small experiment.

We had a web page (of course a good looking one Wink | ;) ) in our previous lesson. It looked like below correct?

Now let's add a universal border in our CSS file.

* {
   border: 1px solid red !important;
}

Save the CSS and refresh your page. You can see that each element has a border and all of them are rectangular boxes.

Understanding the above fact will help you greatly when you design your web pages. Now lets dig deeper into this model.

The gang of four:

There are 4 components to these boxes which affect the Box's size and representation on a page and they are:

  1. Content - Area of the box where the actual content like text, images etc., reside
  2. Padding - Buffer space that clears the main content from the containing box
  3. Border - Surround the content and padding
  4. Margin - Transparent spave that clears the BOX from other boxes (Elements and their wrappers) on the page.
  5. We also have another member here called Mr.Outline. But Ouline is more of a property that doesn't affect the size of the box. Hence we will keep it out of this gang for now. (Will discuss this as a property shortly)

I am sure a picture would help here.. see below. Below lets say we have

  • A div with 300x200px
  • 15px of padding
  • 5px of border
  • 30px of margin
  • Then the total area taken by this div one the page would be
    • Width will be the sum of below (400px)
      • 300px of the content area
      • 2*15px = 30px of padding on both sides
      • 2*5px= 10px of border
      • 2*30px = 60px of margin
    • Similarly the total height would equal to 300px

Lets look each of these properties in the BOX model and how they can be used and to some extent should be used.

Padding:

The portion just after the content and before the borders is defined by the padding property. The padding property creats space around an element's content inside of the borders (or margins if no borders).

Just like other elements the values for padding can be set using lengths or percentages and no-negative values please. Padding starts with a value 0 (Even many of us start with a zero don't we? Smile | :) ) .

Let's create a quick html table, add a row and some cells..

<!DOCTYPE html>
<html>
<head>
    <title>We are BOX-ing (CSS)</title>
    <style>
        body
        {
            background-color:lightgoldenrodyellow;
        }
        table.BoxModel tr td
        {
            border: 1px solid red;
        }
    </style>
</head>
<body>
    <table class="BoxModel">
        <tr>
            <td colspan="4"> <b>Note:</b>CodeProject - HTML CSS : BoxModel
</td>
        </tr>
        <tr>
            <td>Padding</td>
            <td>Border</td>
            <td>Margin</td>
            <td>Outline</td>
        </tr>
    </table>
</body>
</html>

With this it would look something like this

We can see that the borders are very close to the content. So lets add some padding and see what will be the difference.

You could add padding using the shorthand, which means defining all four sides in one line or you could add padding for each side individually. The shorthand syntax is as below, the order of sides in the value is "Top-Right-Bottom-Left". Its clockwise so easy to remember. So lets add the below code to your HTML page.

table.BoxModel tr td
        {
            border: 1px solid red;
            padding-bottom : 2px;
            padding-top: 5px;
            padding-left: 5px;
            padding-right: 2px;
            padding
            /*padding: 5px 5px 5px 5px; -->Shorthand, details below*/
            /*padding: top right bottom left --> Clockwise */
            /*padding: 5px; --> this will set all four sides to 5px*/
        }

And the difference, we have the content comfortably away from the borders.

Borders:

In the above example we already have our border set to 1 px and color red. Lets look at other border properties and experiment with them.

The basic values of a border are:

  • Border-Width
  • Border-Style
  • Border-Color
  • Initial and Inherit just like in other properties. Read more about Initial and Inherit by following the links.
  • CSS3 supports the below 3 properties related to borders and most of the contemperory browers support it. We will include these in our example below.
    • border-radius
    • box-shadow
    • border-image

Below are some of the border styles available with their descriptions.

Value Description
none Default value. Specifies no border
hidden The same as "none", except in border conflict resolution for table elements
dotted Specifies a dotted border
dashed Specifies a dashed border
solid Specifies a solid border
double Specifies a double border
groove Specifies a 3D grooved border. The effect depends on the border-color value
ridge Specifies a 3D ridged border. The effect depends on the border-color value
inset Specifies a 3D inset border. The effect depends on the border-color value
outset Specifies a 3D outset border. The effect depends on the border-color value
initial Sets this property to its default value.
inherit

Inherits this property from its parent element.

The shorthand syntax of the border is

border: border-width border-style border-color;

Lets define 5 different classes and assign them to the 5 boxes we have above: Below are the class names we are going to use and what they will represent. We will use the shorthand syntax to keep it short.

  1. bdGroove: This class will set the border style to groove, color to green, width to 5px. Width also supports some enumerate vales like thin, medium and thick.
  2. bdImage: Border using an image
  3. bdShadow: Border with a shadow
  4. bdradius: Border with a radius of 25px, should round of those sharp edges
  5. bdDotted: A dotted border

Nows lets get the class ready as below.

 .bdGroove
        {
            border-style:groove;
            border: 5px groove red;
        }
        .bdImage
        {
            border-image:url(border.png) 30 30 round;
        }
        .bdShadow
        {
            box-shadow: 10px 10px 5px #888888;
            border: 5px solid red;
        }
        .bdradius
        {
            border-radius:25px;
            border: 5px solid red;
        }
        .bdDotted
        {
            border-style:dotted;
            border: 5px dotted red;
        }

And apply these classes to the table elements, code below.

    <table class="bdShadow">
        <tr>
            <td colspan="4" class="bdGroove"> <b>Note:</b>CodeProject - HTML CSS : BoxModel
</td>
        </tr>
        <tr>
            <td class="bdImage">Padding</td>
            <td class="bdradius">Border</td>
            <td class="bdDotted">Margin</td>
            <td class="bdGroove">Outline</td>
        </tr>
    </table>

And this is what you will see. Image below.

Margin:

As we mentioned earlier Margin just adds white space around an element/box. Margin can be written using short hand with the same clockwise rule. So lets add a 50px Margin to our table above.

Since we are using the bdShadow for the class our code for adding margin will look like this

.bdShadow
        {
            box-shadow: 10px 10px 5px #888888;
            border: 5px solid red;
            margin: 50px 50px 50px 50px;
        }

and the result.

Outline:

Outline can be thought as a border but they donot take up space. They eat into margins, lets add a outline to the bdShadow class to see what I mean.

outline: 25px solid green;

And here is what you will get. You see now the Margin is 50px, but 25px is taken by outline. Essentially making the margin to be 25px.

What if the outline was 50px and margin 25px? Good question, and the answer is Mr.Outline adapts himself and shrinks himself to be 25px. End result, Outline wouldn't take up space exclusively.

Dimension, Display, Positioning, Floating, Align

The Dimension, Display, Positioning, Floating, Align are the properties which greatly impact your Web design and the appearance of your web document. With more and more internet enabled devices coming into existence, your managing the real estate on your page to display your content sensibly and comfortably becomes more important. Let’s look at these one by one before using this in our examples.

Dimension:

As the name suggests Dimension property is used to control the dimension/size of an element. As we know in a 2D space of a web document, the dimension properties could be height and width. However, you can define max and min on both of these properties. Let me list them all in a table with description below.

Property Description Values
height Sets the height of an element auto
length
%

inherit
max-height Sets the maximum height of an element none
length
%

inherit
max-width Sets the maximum width of an element none
length
%

inherit
min-height Sets the minimum height of an element length
%

inherit
min-width Sets the minimum width of an element length
%

inherit
width Sets the width of an element auto
length
%

inherit

Display:

It would be fair to say that Display is one of the most important property used in controlling a layout. Every element’s default display mostly has a value of either inline or block, this default value depends on the type of the element.

In our examples we would use some span elements to apply the display properties that will make the examples short. A span element is used to group in-line elements in a document, it provides no visual change by itself and it’s a way to add a handle to a part of text or simple a part in the document.

Below is a table that explains all the most common display property values and also how they look different when assigned those values.

Value Description Code And How it looks
inline This is the Default value and it sisplays an element as an inline element
<p>Property : <span style="display:inline;background-color:#ff7722;">Inline</span>

Property : Inline : Text after span

block Displays an element as block element like a paragraph <p>
<p>Property : <span style="display:block;background-color:#ff7722;">Block</span>

Property : Block : Text after span

inline-table Displays an element as a inline table element
<p>Property : <span style="display:inline-table;background-color:#ff7722;">Inline Table </span>

Property : Inline Table : Text after span

inline-block Displays an element as a block (like paragraph) but at inline level.
<p>Property : <span style="display:inline-block;background-color:#ff7722;">Inline Block </span>

Property : Inline Block : Text after span

list-item Displays an element as block element like a list-item <li>
<p>Property : <span style="display:list-item;background-color:#ff7722;">List Item</span>

Property : List Item : Text after span

table Displays an element as block element like a table <table>
<div style="display: table;">
<div style="display: table-row;">
<div style="display: table-cell; background-color: #ff7722;">My row1-cell1</div>
My row1-cell1
My row1-cell2
My row2-cell1
My row2-cell2
My row3-cell1
My row3-cell2
table-row Displays an element as block element like a table row <tr>
table Displays an element as block element like a table cell <td>
none Makes an element invisible and frees up the space as apposed visibility:hidden which takes up the space even when the element is hidden
<p>Property : <span style="display:none;background-color:#ff7722;">NONE</span>

Display none example

Property : NONE : Text after span

Visibility Hidden example

Property : Hidden : Text after span

Positioning:

This position property defines where the element would be positioned and relative to what element. Below are the property values and their description

  • Static : This is the default value. All elements will appear in the same order they are defined in the document flow.
  • Absolute: As the name suggest this value defines the absolute position of the element but with respect to its first positioned (not static) ancestor element
  • Fixed: Similar to Absolute these appear at a defined position but in this case relative to the browser window
  • Relative: The element is positioned relative to its normal position, for instance "left:20" adds 20 pixels to the element's LEFT position

Below is a code snippet that would help demonstrate the usage of above values

<!DOCTYPE html>
<html>
<head>
    <style>
        div
        {
            width: 300px;
            border: 1px solid red;
            background-color: #ffd800;
        }
        .rel-left
        {
            position: relative;
            left: 10px;
            bottom: 5px;
            z-index: -1;
        }
        .abs
        {
            position: absolute;
            top: 35px;
            left: 205px;
        }
       .fixed
       {
            position: fixed;
            top: 105px;
            left: 155px;
        }
    </style>
</head>
<body>
    <div>The first DIV</div>
    <div>Div positioned Static</div>
    <div class="rel-left">Div positioned Relative</div>
    <div class="abs">Div positioned Absolute</div>
    <div class="fixed">Div positioned fixed</div>
    <div>The last DIV</div>
</body>
</html>

and below is the result.

Float:

Floating is a property when used would shift/move the element to the left or right of the container. Floating is often used with images when we want to flow the text around the image. The elements before the floated element are not affected but only the ones after will flow around the floated element. As mentioned an element can be horizontally and not vertically.

When multiple elements are floated next to each other in the same direction they stack up until they fill the line, once filled they move downwards. For instance your images displayed in thumbnail view.

We can disallow other floating items to the left or right using clear property. Floating basically has only two properties and they are described below.

Float: This property takes values of left, right, none and inherit. The values left and right basically tell which direction to float the element; none says No-Floating which is the default value and inherit value will inherit the value from its parent element

Clear: This property takes values of left, right, both, none and inherit. As mentioned earlier this property defines whether or not to float other items on either side of the current element.

We will include this as an example in the final html page.

Align:

Aligning a text in HTML is done using two properties namely

  • Text-Align
  • Vertical-Align

Text Align:

Text align is used to align text within a container. It takes the below values and most of us would be already aware of these terms, hence I am trying to keep this short.

Syntax:

text-align: left|right|center|justify|initial|inherit;

Example:

<div style= “text-align: center;”>

TEXT to be centered inside the div

</div>

  • Left: Text aligned to the left of the container.
  • Right: Text aligned to the left of the container.
  • Center: Text is centered inside the container.
  • Justify: Stretches the lines so that each line has equal width (like in newspapers and magazines)
  • Initial: Sets this property to its default value.
  • Inherit: Inherits this property from its parent element.

Vertical-Align:

vertical-align is used to specify two completely different behaviors depending on where it is used

Vertical Align when used within elements like Table cells it would act like float property but vertically instead of horizontally. This is what most of the developers would expect it to do. However when the same property is used with in-line elements like a span within a paragraph it would align that part with respect to the line.

And when used with block level elements it would have no effect, for instance: a small div inside a larger div and want to vertically center the smaller one within, vertical-align is not the one that can help.

With these in mind let’s quickly look at some of the common values that this property can take and what each one of them mean.

  • Baseline: Being the default value this aligns the baseline of the element with the baseline of the parent element.
  • Length: Increses and decreases the position with the length value. Negative values are allowed
  • %: Increses and decreases the position in a percent of the "line-height" property. Negative values are allowed
  • Sub: Subscript alignment
  • Super: Superscript alignment
  • Top: The top of the element is aligned with the top of the tallest element on the line
  • Middle: The element is placed in the middle of the parent element
  • Bottom: The bottom of the element is aligned with the lowest element on the line

Borders:

I have already covered the basics of borders and border styles in the first part of this article. So let’s look at some other ways of using borders.

One of the interesting uses I ever implemented using borders was applying them to elements with zero width and height. This will get us a shape (..we are looking for). Let’s directly jump into a demonstration and it should make it clear as to what we are talking about.

Let’s say we create a div style with zero width and height but 100px of border with different color for each side of the border. Can you guess what would be the result? Here is the code.

  div.something-interesting
{
            width: 0;
            height: 0;
            border: 100px solid;
            border-top-color: #4cff00;
            border-right-color: #0094ff;
            border-bottom-color: #ff006e;
            border-left-color: #ff6a00;
}

It will interesting to see the below result Smile | :) . The reason for the below result is that it was the only way the colors could align.

Now, though it was interesting use of border where do we practically need /use this ?

I can show you couple of ways to use this and you will be free to use your imagination to take this to the next step.

#1: Lets say we have a menu list at the top of the page and we would like to use a indicator as to which menu is currently active. Then we could use the above border style with a modification to make only one of the side with color and others transparent. Below is the code and image to do that.

div.something-interesting
{
    width: 0;
    height: 0;
    border: 100px solid;
    border-color:white;
    border-top-color: #4cff00
}

and below is what we see

If we used similar divs on a page it would look like this

Another example is to make a speech bubble.

Let’s create two classes called bubble and arrow

        .bubble        {
            width: 150px;
            height: 100px;
            background-color: #ff006e;
            border-radius: 10px;
        }
       .arrow
        {
            width: 0;
            height: 0;
            position: absolute;
            left: 50px;;
            border: 10px solid;
            border-color: white;
            border-top-color: #ff006e;
        }

Now in the Html we add two divs.

<div class="bubble"><p style="padding:20px;">Hello there</p></div>

<div class="arrow"/>

And the result: A speech bubble.

CSS Lists and CSS Tables:

CSS Lists:

In our previous article we learnt that there are two kinds of lists in CSS, Ordered(<ol>) and Unordered(<ul>) Lists. Lets dive a bit deeper into the properties of these lists.

The four basic CSS list properties are:

  1. List-style : This is the shorthand which sets all the properties of a list in one line
  2. List-style-image: use to assign a image for the list (bullets)
  3. List-style-position: Defines the position of the bullets with respect to the actual list text
  4. List-style-type: This defines the type of list-item type(bullet, numbers etc)

Since List-style is a short hand we will look at the other three properties and their values first and then look the the syntax for the shorthand.

  • List-style-image: The most used values on this are none and url. None just makes the list without any bullets and url will specify the image to be used in place of bullets.
    1. Syntax:
      1. list-style-image: none|url|initial|inherit; 
  • List-style-position: Here inside and outside are the most used values with outside being the default. Below image better says what these mean.

  • List-style-type: The values to this property is pretty exhaustive, this property defines on what type of bullets or number you like to be displayed. Below are some value and their descriptions
    • circle The marker is a circle
    • decimal The marker is a number
    • decimal-leading-zero The marker is a number with leading zeros (01, 02, 03, etc.)
    • georgian The marker is traditional Georgian numbering
    • lower-alpha The marker is lower-alpha (a, b, c, d, e, etc.)
    • lower-roman The marker is lower-roman (i, ii, iii, iv, v, etc.)
    • none No marker is shown
    • square The marker is a square
    • upper-alpha The marker is upper-alpha (A, B, C, D, E, etc.)
    • upper-latin The marker is upper-latin (A, B, C, D, E, etc.)
    • upper-roman The marker is upper-roman (I, II, III, IV, V, etc.)
  • List-style: As we saw earlier this is the short hand for declaring all the above 3 properties together. Syntax is as below.
    • List-style: list-style-type list-style-position list-style-image;

CSS Tables:

Though I don’t have a strong answer on why use CSS tables while we can use the HTML tables which are more popular and easy to use. I will try and explain what these CSS Tables are and how to use them. CSS Tables are built using the table values on the display properties. I have covered the different values of display property that relates to table HERE.

One of the nice features of CSS is ability to use the visbity:collapse property, which will help collapse one or more columns.In my opinion, At this point CSS tables don’t provide enough advantages over html tables when it comes to layout.

Now let’s look at a quick example on how to build a CSS table and move on to our next topic. Below example defines 3 styles, one each for table, cell and row. As you can see we are applying the styles to the divs that are being built using the display property.

<!DOCTYPE html !>
<html >
<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <title>CSS Table Example</title>
    <style type="text/css">
        div
        {
            background-color: brown;
            width: 5px;
            height: 5px;
        }
        .cell
        {
            display: table-column;
            float: left;
            width: 200px;
            border:2px solid yellow;
        }
        .row
        {
            border:2px solid red;
            display: table-row;
        }
        .table
        {
            border:2px solid green;
            display: table;
        }
    </style>
</head>
<body>
    <div class="table">
        <div class="row">
            <div class="cell">col 1</div>
            <div class="cell">col 2</div>
            <div class="cell">col 3</div>
            <div class="cell">col 4</div>
        </div>
        <div class="row">
            <div class="cell">col 1</div>
            <div class="cell">col 2</div>
            <div class="cell">col 3</div>
            <div class="cell">col 4</div>
        </div>
        <div class="row">
            <div class="cell">col 1</div>
            <div class="cell">col 2</div>
            <div class="cell">col 3</div>
            <div class="cell">col 4</div>
        </div>
        <div class="row">
              <div class="cell">col 1</div>
            <div class="cell">col 2</div>
            <div class="cell">col 3</div>
            <div class="cell">col 4</div>
        </div>
    </div>
</body>
</html>

Below is the result.

Divs and Spans:

Div:

Div is short form of division. Div is usually used as a container to separate group of elements and apply styles and actions to a group together. Div is a block level container which means that there will be new line after the end of div tag. Most of the properties explained in the box model chapter of this lesson can be applied to a div and divs can be nested within one another. To use div we surround the elements with <div> and <\div>, example below

<div>
<p>para 1</p>
<div> nested div
<p> para 2</p>
<p>para 3</p>
</div>
</div>

A div can be assigned anid, e.g. <div id="Div1">and a class, e.g. <divclass="mainDiv">. Both of these attributes can then be selected using CSS or modified using JavaScript.

This arrangement enables us to define the styles of entire sections of the HTML.

Span:

The span element is very similar to Div meaning just like div even span can apply styles to all the elements it encloses at once. The main difference between span and div is that span is an inline element where as div is a block element and hence span doesn’t do any formatting of its own unlike div which includes paragraph break and line break at the end. Below is an example on how to use span with <span> and </span> tags:

<div id="Div1">
<p><span class=”highlight”>within Span</span> Outside span.</p>
</div>


I have attached the source code for a static HTML and CSS which uses most of the above explained properties. See below on how to use the source code.

Using the code

Download the zip file and unzip the contents into C drive. You can then view your html in any of the browsers directly. The images are in the image folder and the CSS stylesheet is located under the CSS folder.

Points of Interest

Learnt one big lesson. CSS cannot be covered or learnt through one chapter. Even though the most common things can be learnt very quickly there are so many interesting uses of CSS that are worth exploring and implementing. I enjoyed writing this article the most, though I couldn't help but make it longer than I wanted it to be. This article only introduces to the concepts and in no means a exhaustive guide. This is targetted for beginners to get a kick start to explore the world of CSS.

History

Initial Version - 4/6/2014 - Guruprasad.kb

License

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

Share

About the Author

Guruprasad.K.Basavaraju
Software Developer (Senior)
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionVery NIce Article Guru Pin
Prabhakar.Vijendar11-Jun-14 0:27
memberPrabhakar.Vijendar11-Jun-14 0:27 
AnswerRe: Very NIce Article Guru Pin
Guruprasad.K.Basavaraju11-Jun-14 6:55
memberGuruprasad.K.Basavaraju11-Jun-14 6:55 
GeneralGreat Read! Pin
Kevin Priddle10-Apr-14 18:05
staffKevin Priddle10-Apr-14 18:05 
GeneralRe: Great Read! Pin
Guruprasad.kb11-Apr-14 4:40
memberGuruprasad.kb11-Apr-14 4:40 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150731.1 | Last Updated 7 Apr 2014
Article Copyright 2014 by Guruprasad.K.Basavaraju
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid