Click here to Skip to main content
14,971,280 members
Articles / Web Development / HTML5
Article
Posted 2 Apr 2014

Tagged as

Stats

20.9K views
408 downloads
18 bookmarked

Beginning with HTML and CSS - Part 3/12 - Styling Your First Web Page

Rate me:
Please Sign up or sign in to vote.
4.90/5 (15 votes)
7 Apr 2014CPOL12 min read
This article is a startup kit for anyone who is new to HTML and CSS.

Introduction

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

This article is intended to introduce the

Background

The basics of HTML will help understanding this article better. Below are the links

Beginning with HTML and CSS - Part 1/12 - Writing Your First Code

Beginner's Guide to HTML5 & CSS3 - Part 2 of 12 - Building on Basics by James Jensen

Styling in HTML

While we now know that HTML defines the structure and content, CSS defines the presentation of the same in a Web document. Styling in HTML can be achieved with a CSS sheet by applying the styles directly at the element level.

For example an unordered list may look like below with out styles.

HTML
<ul>
    <li>Georgia</li>
    <li>Oregon</li>
    <li>Washington</li>
    <li>Nevada</li>
    <li>California</li>
</ul>

Outcome will be like below.

Image 1

Now lets try to make it look a little better.

We shall add Borders to UL and LI elements and also add different border colors to alternative LI elements

HTML
<ul style="border:double;text-align:left;width:10%">
       <li style="border:groove;border-bottom-color:aquamarine;">Georgia</li>
       <li style="border:groove;border-bottom-color:darkorange;">Oregon</li>
       <li style="border:groove;border-bottom-color:aquamarine;">Washington</li>
       <li style="border:groove;border-bottom-color:darkorange;">Nevada</li>
       <li style="border:groove;border-bottom-color:aquamarine;">California</li>
   </ul>

Now doesn't this look better ? :)

Image 2

That's a quick example of what styling is. By now you might have also noticed that we are repeating some of the stlye tags on LI elements, if we had to define styles globally we can do that using the Cascading style sheets. The styles in the CSS can be defined by selectors.

What are Cascading Style Sheets (CSS)

CSS document are the ones which contain the styling rules that will be applied to an HTML (or XML, along with a few other formats). Now why do we call them Cascading Style Sheets and not just "Style Sheets". We say these style sheets are cascading because the sheets can apply formatting when more than one style applies. For instance, if you say all paragraphs should have blue font, but you specifically single out one paragraph to have red font, CSS can do that!

More than one Stlye Sheet can be applied to a page. For instance you could have a Common style sheet defined at the master page level and a more specific styles for a single page. Or link multiple style sheets in a page. Cascading rules will determine which style is to be applied to an element.

So what are these rules?

I will try to keep this section simple.

Since there are multiple methods to specify style sheets. Like :

  • Link Style Sheets
HTML
<head>    <link rel="stylesheet" type="text/css" href="HelloWorld.css"></head>
  • Embed Style Sheets (using the HTML STYLE element [-->Index DOT Html])
HTML
<head>
    <style>
        hr {color:sienna;}
        p {margin-left:20px;}
        body {background-image:url("images/background.gif");}
    </style>
</head>
  • Imported Style Sheets
HTML
@import "HelloWorld.css";
  • Inline Style Rules
HTML
<p style="color:sienna;margin-left:20px;">This is a paragraph.</p>

The order in which the styles are prioritized/weighed are as below, 1 being the most important.

  1. Inline Style rules
  2. Internal style sheets (Embed or linked)
  3. External style sheets (@import)
  4. Browser default styles (Example: Blue links)

Lets say if two rules end up with same weight, then the latter wins. Imported style sheets and internal style sheets carry the same weight but since per specs the import tags comes before declaring any styles the internal styles will take precedence.

Also when styles are defined using a #id selector it will carry the same weight as inline styles. We will look at what are selectors shortly.

Once the above priorities are determined, the next level of priorities are at the page level. We could call them internal priorities. Below is a general list of internal priorities. Again, 1 being most important.

  1. #id
  2. .class
  3. element (could be nested, in which case the last style in the nest takes effect)

Now, time for the MASTER KEY. (!important)

The !important rule is the way to override all of this. Putting !important after the declaration, but before the semicolon will simply override all previous cascade and give it the highest priority. If !important is specified more than once for the same element, they will fall back to the normal cascading rules. Also, declaring a shorthand property to be !important is equivalent to declaring all of its sub-properties to be !important.

Inheritance :

They style values are inherited from its parent’s element in the document tree. The properties with value “inherit” will inherit its parent’s value for the same property into a computed value. Note that computed is in BOLD :) . Here’s a basic example to demonstrate why its in bold.

Below code will simply render the text "big text" in font size 10, this is simple inheritance.

HTML
<p style="font-size: 10px;"><span>big text</span></p> 

But when the below code with style for span is rendered the font size of the text will be 20px, this is inheritance with computed value.

HTML
<p style="font-size: 10px;"><span style="font-size: 200%;">big text</span></p>  

How does a CSS get linked to a HTML file ?

This is how. There are multiple ways to do it (refer above). Below is what we will use.

HTML
<link rel="stylesheet" type="text/css" title="Hello World style sheet" href="./CSS/HelloWorld.css">

You add the above line inside the Head tag of your document and your page now has a style sheet named Helloworld.CSS. Quite simple, isn't it ?

Basic CSS Syntax:

There are three parts which constitutes a CSS rule.

  1. Selector: A selector is an HTML tag at which style will be applied. This could be any tag like <div>,<table> etc.
  2. Property: A property is a type of attribute of HTML tag. Put simply, all the HTML attributes are converted into CSS properties. They could be color, font, border etc.
  3. Value: Values are assigned to properties. For example color property can have value either red or #FFFFFF etc.

So the basic syntax would be selector { property: value }

An example for defining a border for a table would be table{ border :1px solid #C00; }

In the above example table is the selector, border is a property and the rest property's value.

Selectors :

We can define selectors in various simple ways based on our need and comfort. Below are some selectors.

The Type Selector:

We already saw this in our example. table{ border :1px solid #C00; } , we are simply selecting by type "table" and assigning a border property here. Same can be done for any type of elements, for instance to make sure all h1 headers have a particular color we can say

HTML
h1 { color: #36CFFF; } 

The Universal Selector:

The name says it all, this selector will select all the elements instead of selecting a particular type (element). Here is how to use it

HTML
* {   color: #000000; }

The Class Selectors:

You can define style rules based on the class attribute of the elements. Any element with a class assigned will be formatted according to the defined rule.

HTML
.black {  color: #000000; } 
Usage: 
<table class="black"> ....</table> 

This rule renders the content in black for every element with class attribute set to black in our document. You can make it a bit more particular. For example:

HTML
h1.black {  color: #000000; } 
Usage: 
<h1 class="black">I am a black header-1</h1>   

This rule renders the content in black for only <h1> elements with class attribute set to black. If a table used this class then there will be no effect.

You can apply more than one class selectors to given element. Consider the following example :

HTML
<h1 class="center bold">This header will be styled by the classes center and bold.
</h1> 

The ID Selectors:

Selection based on the id attribute of the elements. All the elements having that id will be formatted according to the defined rule.

HTML
#black {  color: #000000; } 
Usage:  
<table id="black"> ....</table>  

This rule renders the content in black for every element with id attribute set to black in our document. You can make it a bit more particular. For example:

CSS
h1#black {  color: #000000; } 
Usage: 
<h1 id="black"> ....</h1>   /*Style will be applied */ 
<h1> ....</h1>   /*Style will NOT be applied */ 

This rule renders the content in black for only <h1> elements with id attribute set to black.

The Descendant Selectors:

Suppose you want to apply a style rule to a particular element only when it lies inside a particular element. As given in the following example, style rule will apply to <em> element only when it lies inside <ul> tag.

ul em { color: #000000; }

Also to note here is that the true power of id selectors is when they are used as the foundation for descendant selectors, For example:

CSS
#BlackGrid td {  color: #000000; }

In this example all td's will be displayed in black color only when those td's lie within tags (Table/TR) having id attribute set to "BlackGrid".

The Child Selectors:

These are almost like descendants but have different functionality. Consider the following example:

CSS
body > p {  color: #000000; }

This rule will render all the paragraphs in black if they are direct child of <body> element. Other paragraphs put inside other elements like <div> or <td> etc. would not have any effect of this rule.

The Attribute Selectors:

You can also apply styles to HTML elements with particular attributes. The style rule below will match all div elements that has a brand attribute with a value of text:

CSS
div[brand]{  color: #000000; } /*Selects all divs with a brand attribute */ 
div[brand="honda"]{  color: #000000; } /*Selects all divs with brand attribute is honda */ 
div[brand~="toyota"]{  color: #ffffff; } /*Selects all divs with brand attribute is not toyota*/  

Group Selectors:

You can just apply a group of style rules to a group of elements or classes. Examples below

CSS
div, table, section {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}
#content, #footer, #header {
position: absolute;
left: 510px;
width: 200px;
} 

Also you might be wondering what is the unit of measure in CSS, because some places I have used .em and others px . Below table should clear your doubts. (I am assuming its self explanatory)

Unit Description Example
% Defines a measurement as a percentage relative to another value, typically an enclosing element. p {font-size: 16pt; line-height: 125%;}
cm Defines a measurement in centimeters. div {margin-bottom: 2cm;}
em A relative measurement for the height of a font in em spaces. Because an em unit is equivalent to the size of a given font, if you assign a font to 12pt, each "em" unit would be 12pt; thus, 2em would be 24pt. p {letter-spacing: 7em;}
ex This value defines a measurement relative to a font's x-height. The x-height is determined by the height of the font's lowercase letter x. p {font-size: 24pt; line-height: 3ex;}
in Defines a measurement in inches. p {word-spacing: .15in;}
mm Defines a measurement in millimeters. p {word-spacing: 15mm;}
pc Defines a measurement in picas. A pica is equivalent to 12 points; thus, there are 6 picas per inch. p {font-size: 20pc;}
pt Defines a measurement in points. A point is defined as 1/72nd of an inch. body {font-size: 18pt;}
px Defines a measurement in screen pixels. p {padding: 25px;}

Backgrounds, Texts and Fonts:

The Backgrounds, Text and Fonts are the most commonly styled properties. Lets look at them one by one.

Backgrounds : The Background property as the name suggests is used to define the background effects of an element.

There are number of background properties, below are some of them.

  • background-color : Specifies the background color of an element.
  • background-image : Specifies an image to use as the background of an element. By default, the image is repeated so it covers the entire element.
  • background-repeat : Repeats an image both horizontally and vertically
  • background-position : Specifies the position of the image.
  • Background - Shorthand property : A shortcut to combine all above and some more property values into one. Property name would be just "Background". Below is the order of property values.
    1. background-color
    2. background-image
    3. background-repeat
    4. background-attachment
    5. background-position

Below are some examples for above properties.

CSS
body {background-color:#b0c4de;} /*Color*/
h1 {background-color:#6495ed;}/*Color*/
p {background-color:#e0ffff;}/*Color*/
div {background-color:#b0c4de;}/*Color*/
body {background-image:url("superimage.gif");} /*Image*/
body
{
background-image:url("myPicture.png");
background-repeat:repeat-x;
}
body
{
background-image:url("img_tree.png");
background-repeat:no-repeat;
background-position:right top;
}
body {background:#ffffff url("img_tree.png") no-repeat right top;} /*Short hand*/ 

Text: Below are some of the text properties and their description

  • color : Sets the color of text
  • direction : Specifies the text direction/writing direction
  • letter-spacing : Increases or decreases the space between characters in a text
  • line-height : Sets the line height
  • text-align : Specifies the horizontal alignment of text
  • text-decoration : Specifies the decoration added to text
  • text-indent : Specifies the indentation of the first line in a text-block
  • text-shadow : Specifies the shadow effect added to text
  • text-transform : Controls the capitalization of text
  • unicode-bidi : Used together with the direction property to set or return whether the text should be overridden to support multiple languages in the same document
  • vertical-align : Sets the vertical alignment of an element
  • white-space : Specifies how white-space inside an element is handled
  • word-spacing : Increases or decreases the space between words in a text

Font : Similar to Text above I am listing the Font properties below.

  • font : Sets all the font properties in one declaration
  • font-family : Specifies the font family for text
  • font-size : Specifies the font size of text
  • font-style : Specifies the font style for text
  • font-variant : Specifies whether or not a text should be displayed in a small-caps font
  • font-weight : Specifies the weight of a font

Where and How to use CSS

With all the above information and our understanding about HTML from previous lessons. Lets try to make a good looking HTML page by applying some of the styles we learnt above.

Below is how the HTML file looks like without styling.

Image 3

First things first, lets add a header, section, aside and footer to the page.

Now lets add the below styles to elements below.

HTML
<body style="color:#444;     font:1em/1.5 Georgia, "Times New Roman", Times, serif;"> 
<table style="width:98%"><tr><td style="text-align:center"><a href="http:\\Codeproject.com"><img src="images/CodeprojectBob.png" /></a></td></tr></table> 
 <section style="background:#e7e7e7;     border:1px solid #e7e7e7;         float:left;     margin:0 20px 0 0;     padding:19px;         width:560px;"> 
<article style="background:#f7f7f7;     border:1px solid #f7f7f7;     padding:19px;"> 

If you are using IE8 and below you will need to add the below code just before closing the head tag to support the new HTML5 tags.

HTML
<!--[if lt IE 9]>
<script>
document.createElement('header');
document.createElement('nav');
document.createElement('section');
document.createElement('article');
document.createElement('aside');
document.createElement('footer');
document.createElement('hgroup');
</script>
<![endif]--> 

Now you see the page looks better, but what if the page grows and we have more tables, more divs, more sections ? We dont want to remember what exact style to apply to each element type and more over when we decide to change the style we dont want to do that to every element. That's where CSS comes to our rescue. Now lets create a CSS with most of the elements covered. We will use different types of selectors as we saw earlier.

Create a new file called HelloWorld.css inside your Helloworld/CSS folder and copy paste the below CSS styles. I have tried putting comments to make it easier to follow, please comment if you need more info.

CSS
 #main-header header.realHeader {
    background-image: url("../images/CodeprojectBob.png");
    top: 0;
    height:100px;
    width: 98%;
    background-position:center; 
    background-repeat:repeat-x;
}
/*type selectors*/
html {
    font-size:100%;
}
body {
    color:#444;     font:1em/1.5 Georgia, "Times New Roman", Times, serif;
}
section {
    background:#e7e7e7;     border:1px solid #e7e7e7;     -moz-border-radius:10px;     -webkit-border-radius:10px;     float:left;     margin:0 20px 0 0;     padding:19px;         width:560px;
}
aside {
    float:left;
    width:300px;
}
article {
    background:#f7f7f7;     border:1px solid #f7f7f7;     -moz-border-radius:10px;     -webkit-border-radius:10px;     padding:19px;
}
footer {
    clear:left;
    padding:20px 0 0;
}
span {
    font-weight:bold;
}
/*id selectors*/
#wrap {
    background:#eee;     border:1px solid #eee;     -moz-border-radius:10px;     -webkit-border-radius:10px;     margin:20px auto;     overflow:hidden;     padding:19px;     width:920px;
}
#menu a {
    font-size: 1.3em;
    font-weight: 600;
    margin: 0 0 5px;
    padding: 0;
    padding-left:100px;
    text-align: left;
}
#menu tr a{
    display: inline;
    list-style: none;
    padding-left: 15px;
}

#menu tr td a {
        background: none;
        color: #999;
        text-decoration: none;
    }
#menu tr td a:hover {
        color: #333;
        text-decoration: none;
    }
/*Class selector*/
table.results {
    width: 90%;
    margin: 0px auto 20px auto; /* center the table */
    border-collapse: collapse; 
    border: 2px solid blue;
    padding: 15px 15px 15px 15px;
    }
table.results tr.alt-item /*all table tr with class alt-item*/
{
    background-color:lightblue;
}
table.results tr td /*all table td with class results*/
{
    padding: 2px;
    height: 5px;
    color: #404040;
    border: 2px solid blue;
}
table.results thead tr td { /*all table headers td with class results*/
    background-color: #0F74BB;
    color: white;
    border: 2px solid blue;
}
div.grid {
    text-align: left;
    margin: 0px 40px 0px 20px; /* center the table */
    border: 2px solid RED;
    padding: 15px 15px 15px 15px;
} 

Now add the below line just before closing your head tag. This will link your css to your html page.

HTML
<link rel="stylesheet" type="text/css" title="Hello World style sheet" href="./CSS/HelloWorld.css"> 

now if you open your webpage. below is what you see.

Ain't that pretty ? :)

Image 4

There endeth the lesson. See you all in my next part of this article..!! :)

Points of Interest

Understanding Cascading priority gets really confusing, it takes a while to get used to counting points which determines the priority.

History

v0.1 - Initial version - Guruprasad KB - 04/02/2014

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

Comments and Discussions

 
GeneralMy vote of 2 Pin
Kornfeld Eliyahu Peter5-Apr-14 8:41
professionalKornfeld Eliyahu Peter5-Apr-14 8:41 
GeneralRe: My vote of 2 Pin
Guruprasad.K.Basavaraju5-Apr-14 9:52
professionalGuruprasad.K.Basavaraju5-Apr-14 9:52 
GeneralRe: My vote of 2 Pin
Kornfeld Eliyahu Peter5-Apr-14 10:30
professionalKornfeld Eliyahu Peter5-Apr-14 10:30 
QuestionGood article Pin
deleted_user_2-Apr-14 17:37
Memberdeleted_user_2-Apr-14 17:37 
AnswerRe: Good article Pin
Guruprasad.K.Basavaraju3-Apr-14 3:44
professionalGuruprasad.K.Basavaraju3-Apr-14 3:44 

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

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