CSS Introduction

CSS, or Cascading Styles Sheets, is a way to style and present HTML. Whereas the HTML is the meaning or content, the style sheet is the presentation of that document. Cascading Style Sheets (CSS) is a fantastic tool to add layout to your websites. It can save you a lot of time and it enables you to design websites in a completely new way. CSS is a must for anyone working with web design. This tutorial will get you started with CSS in just a few hours. It is easy to understand and it will teach you all the sophisticated techniques. Learning CSS is fun. As you go along through the tutorial, remember to take enough time to properly experiment with what you learn in each lesson. Using CSS requires basic experience with HTML. If you are not familiar with HTML, please start with our HTML tutorial before moving on to CSS.

Which software do I need?

Please avoid using software such as FrontPage, DreamWeaver or Word with this tutorial. Advanced software will not help you learn CSS. Instead, it will limit you and slow down your learning curve significantly. All you need is a free and simple text editor. For example, Microsoft Windows comes with a program called Notepad. It is usually located in Accessories in the start menu under Programs. Alternatively, you can use a similar text editor e.g. Pico for Linux or Simple Text for Macintosh. A simple text editor is ideal for learning HTML and CSS because it doesn't affect or change the codes you type. That way, your successes and errors can only be attributed to yourself - not the software. You can use any browser with this tutorial. We encourage you to always keep your browser updated and use the latest version. A browser and a simple text editor is all you need. Let's get started!

What is CSS?

Maybe you already heard about CSS without really knowing what it is. In this lesson you will learn more about what CSS is and what it can do for you. CSS is an acronym for Cascading Style Sheets.

What can I do with CSS?

CSS is a style language that defines layout of HTML documents. For example, CSS covers fonts, colours, margins, lines, height, width, background images, advanced positions and many other things. Just wait and see! HTML can be (mis-)used to add layout to websites. But CSS offers more options and is more accurate and sophisticated. CSS is supported by all browsers today. After only a few lessons of this tutorial you will be able to make your own style sheets using CSS to give your website a new great look.

What is the difference between CSS and HTML?

HTML is used to structure content. CSS is used for formatting structured content. Okay, it sounds a bit technical and confusing. But please continue reading. It will all make sense to you soon. Back in the good old days when Madonna was a virgin and a guy called Tim Berners Lee invented the World Wide Web, the language HTML was only used to add structure to text. An author could mark his text by stating "this is a headline" or "this is a paragraph" using HTML tags such as <h1> and <p>. As the Web gained popularity, designers started looking for possibilities to add layout to online documents. To meet this demand, the browser producers (at that time Netscape and Microsoft) invented new HTML tags such as for example <font> which differed from the original HTML tags by defining layout - and not structure. This also led to a situation where original structure tags such as <table> were increasingly being misused to layout pages instead of adding structure to text. Many new layout tags such as <blink> were only supported by one type of browser. "You need browser X to view this page" became a common disclaimer on web sites. CSS was invented to remedy this situation by providing web designers with sophisticated layout opportunities supported by all browsers. At the same time, separation of the presentation style of documents from the content of documents, makes site maintenance a lot easier.

Why to Use CSS and Which benefits CSS gives me?

CSS was a revolution in the world of web design. The concrete benefits of CSS include:

  1. control layout of many documents from one single style sheet;
  2. more precise control of layout;
  3. apply different layout to different media-types (screen, print, etc.);
  4. numerous advanced and sophisticated techniques.
  5. CSS separates your content from presentation (think MVC).
  6. With CSS an entire web site can change look by changing one file
  7. Using CSS can lower your bandwidth costs.
  8. Your HTML is easier to read and understand making maintenance cheaper.
  9. People with disabilities can access your pages easier.
  10. Organizations can share the same style across web sites.
  11. Menus can be created without javascript.

Why CSS?

CSS is used to style and present HTML. Whereas the HTML is the  content, the style sheet is the presentation of that document. Styles are completely different from HTML, they have a format of ‘property: value’ and most properties can be applied to most HTML tags.

Selectors, Properties, and Values

 Selectors are the names given to styles in within style sheets. Let we first concentrating on HTML selectors, which are the names of HTML tags and are used to change the style of a specific type of html element.

How does CSS work?

In this lesson you will learn how to make your first style sheet. You will get to know about the basic CSS model and which codes are necessary to use CSS in an HTML document. Many of the properties used in Cascading Style Sheets (CSS) are similar to those of HTML. Thus, if you are used to use HTML for layout, you will most likely recognize many of the codes. Let us look at a concrete example.

The basic CSS syntax

Let's say we want a nice red color as the background of a webpage:

Using HTML we could have done it like this:


	<body bgcolor="#FF0000">
	
	

With CSS the same result can be achieved like this:

	
	body {background-color: #FF0000;}
	
	

As you will note, the codes are more or less identical for HTML and CSS. The above example also shows you the fundamental CSS model:

Figure explaining selector, property and value

But where do you put the CSS code? This is exactly what we will go over now.

Grouping Selectors

In the example above we have chosen to style the <h1> tag blue. If we also wanted to style the <h2> and <h3> tags to be blue as well we could do this in one of two ways. We could either write out an individual selector-declaration for each case or we could combine all of our selectors into one statement. So for example the following three statements are the equivalent of the single statement following:

h1 { color: blue; }
h2 { color: blue; }
h3 { color: blue; }  
h1, h2, h3 { color: blue; }

Please note the commas that separate the selectors. Without the commas the result would be something entirely different.

The ability to group selectors and declarations is one of the great shorthand features of CSS.

It is also possible to mix the two methods of writing declarations so that one statement groups selectors with shared properties and another statement declares a property for a single selector. In below example , all header tags are styled red but the <h3> tag is also styled to be strike.

h1, h2, h3 { color: red; }
h3 { text-decoration: strike; }

Grouping Declarations

In addition to grouping selectors we can also group our declarations which is quite useful since any one selector may have quite a few properties that may need to be styled. Keeping in mind the syntax requirements mentioned above there are two general ways of grouping our declaration - as one long stream of properties and values or as a vertical list. Both accomplish exactly the same thing although the vertical list is generally more readable. So for example, the following two statements equally style a number of the properties of the paragraph tag <p>:

p { color: red; font-size: 10pt; margin-right: 10pt; background-color: white; padding: 10pt; }

p {
    color: red;
    font-size: 10pt;
    margin-right: 10pt;
    background-color: white;
    padding: 10pt;
    }

Now you have written css how to apply now?

Applying CSS to an HTML document

There are three ways you can apply CSS to an HTML document. These methods are all outlined below. We recommend that you focus on the third method i.e. external.

Method 1: In-line (the attribute style)

One way to apply CSS to HTML is by using the HTML attribute style. Building on the above example with the red background color, it can be applied like this:

<html>
	  <head>
		<title>Example</title>
	  </head>
	  <body style="background-color: #FF0000;">
		<p>This is a red page</p>
	  </body>
	</html>
	

Method 2: Internal (the tag style)

Another way is to include the CSS codes using the HTML tag <style>. e.g like this:

	<html>
	  <head>
		<title>Example</title>
		<style type="text/css">
		  body {background-color: #FF0000;}
		</style>
	  </head>
	  <body>
		<p>This is a red page</p>
	  </body>
	</html>
	

Method 3: External (link to a style sheet)

The recommended method is to link to a so-called external style sheet. Throughout this tutorial we will use this method in all our examples. An external style sheet is simply a text file with the extension .css. Like any other file, you can place the style sheet on your web server or hard disk. Suppose, let's say that our  style sheet is named master.css and is located in a folder named css. The situation can be illustrated like this:

The folder "style" containing the file "style.css"

The trick is to create a link from the HTML document (default.htm) to the style sheet (style.css). Such link can be created with one line of HTML code:

 <link rel="stylesheet" type="text/css" href="css/master.css" />
	

Remeber how the path to our style sheet is indicated using the attribute href. The line of code must be inserted in the header section of the HTML code i.e. between the <head> and </head> tags. Like this:

	<html>
	  <head>
		<title>My document</title>
		<link rel="stylesheet" type="text/css" href="css/master.css" />
	  </head>
	  <body>
	  ...
	

This link tells the browser that it should use the layout from the CSS file when displaying the HTML file.
The really smart thing is that several HTML documents can be linked to the same style sheet. In other words, one CSS file can be used to control the layout of many HTML documents.

Figure showing how many HTML documents can link to the same style sheet

This technique can save you a lot of work. If you, for example, would like to change the background color of a website with 100 pages, a style sheet can save you from having to manually change all 100 HTML documents. Using CSS, the change can be made in a few seconds just by changing one code in the central style sheet. Let's put what we just learned into practice.

Try it yourself

Open Notepad (or any text editor you are comfortable with) and create two files - an HTML file and a CSS file - with the following contents:

default.htm

	<html>
	  <head>
		<title>My document</title>
		<link rel="stylesheet" type="text/css" href="style.css" />
	  </head>
	  <body>
		<h1>My first stylesheet</h1>
	  </body>
	</html>
	

style.css

	body {
	  background-color: #FF0000;
	}
	

Now place the two files in the same folder. Remember to save the files with the right extensions (respectively ".htm" and ".css") Open default.htm with your browser and see how the page has a red background. Great! You have made your first style sheet!

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.

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

This will apply the given values to the font-size and color properties to the body selector. So basically, when this is applied to an HTML document, text between the body tags (which is the content of the whole window) will be 14 pixels in size and navy in color.

Lengths and Percentages

There are many property-specific units for values used in CSS, but there are some general units that are used by a number of properties and it is great to familiarize.

  1. px (such as font-size: 12px) is the unit for pixels.
  2. em (such as font-size: 2em) is the unit for the calculated size of a font. So “2em”, for example, is two times the current font size.
  3. pt (such as font-size: 12pt) is the unit for points, for measurements typically in printed media.
  4. % (such as width: 80%) is the unit for… wait for it… percentages.

Other units are pc (picas), cm (centimeters), mm (millimeters) and in (inches). When a value is zero,it is just zero(0) not (0px) i mean, no need to state a unit.

Colors

CSS brings about 17000000 colors to your disposal. They might be in the form of form of a name an RGB (red/green/blue) value or a hex code. The following values, to specify full-on as red-as-red-can-be, all produce the same result:

  1. red
  2. rgb(255,0,0)
  3. rgb(100%,0%,0%)
  4. #ff0000
  5. #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.

With the possible exception of black and white, color names have limited use in a modern, well-designed web sites because they are so specific and limiting.

The three values in the RGB value are from 0 to 255, 0 being the lowest level (no red, for example), 255 being the highest level (full red, for example). These values can also be a percentage. Hexadecimal (previously and more accurately known as “sexadecimal”) is a base-16 number system. We are generally used to the decimal number system (base-10, from 0 to 9), but hexadecimal has 16 digits, from 0 to f. The hex number is prefixed with a hash character (#) and can be three or six digits in length. Basically, the three-digit version is a compressed version of the six-digit (#ff0000 becomes #f00, #cc9966 becomes #c96, etc.). The three-digit version is easier to decipher (the first digit, like the first value in RGB, is red, the second green and the third blue) but the six-digit version gives you more control over the exact color.

CSS3, the latest version of CSS, also allows you to define HSL colors - hue, saturation and lightness.

color and background-color

Colors can be applied by using color and background-color (note that this must be the American English “color” and not “colour”). A blue background and yellow text could look like this:

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

These colors might be a little too harsh, so you could change the code of your CSS file for slightly different shades:

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

h1 {
    color: #ffc;
    background-color: #009;
}

Save the CSS file and refresh your browser. You will see the colors of the first heading (the h1 element) have changed to yellow and blue. You can apply the color and background-color properties to most HTML elements, including body, which will change the colors of the page and everything in it.

Text

You can alter the size and shape of the text on a web page with a range of properties.

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. This is useful because different computers sometimes have different fonts installed. So font-family: arial, helvetica, serif, will look for the Arial font first and, if the browser can’t find it, it will search for Helvetica, and then a common serif font. Note: if the name of a font is more than one word, it should be put in quotation marks, such as font-family: "Times New Roman".

You can use a wider selection than the “safe” fonts using several methods outlined in the CSS Advanced Tutorial but if you’re just getting to grips with CSS, we suggest sticking with this basic standard approach for the moment.

font-size

The size of the font. Be careful with this - text such as headings should not just be an HTML paragraph (p) in a large font - you should still use headings (h1, h2 etc.) even though, in practice, you could make the font-size of a paragraph larger than that of a heading (not recommended for sensible people).

font-weight

This 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.

Play around with these font-weight values if you want see their effect but, keep in mind, that some older browsers become a little confused with anything other than bold and normal so we suggest sticking to those unless you’re a typography ninja.

font-style

This states whether the text is italic or not. It can be font-style: italic or font-style: normal.

text-decoration

This states whether the text has got a line running under, over, or through it.

  1. text-decoration: underline, does what you would expect.
  2. text-decoration: overline places a line above the text.
  3. text-decoration: line-through puts a line through the text (“strike-through”).

This property is usually used to decorate links and you can specify no underline with text-decoration: none.

Underlines should only really be used for links. They are a commonly understood web convention that has lead users to generally expect underlined text to be a link.

text-transform

This will change the case of the text.

  1. text-transform: capitalize turns the first letter of every word into uppercase.
  2. text-transform: uppercase turns everything into uppercase.
  3. text-transform: lowercase turns everything into lowercase.
  4. text-transform: none I’ll leave for you to work out.

So, a few of these things used together might look like this:

body {
    font-family: arial, helvetica, sans-serif;
    font-size: 14px;
}

h1 {
    font-size: 2em;
}

h2 {
    font-size: 1.5em;
}

a {
    text-decoration: none;
}

strong {
    font-style: italic;
    text-transform: uppercase;
}

Text spacing

Before we move on from this introduction to styling text, a quick look at how to space out the text on a page: The letter-spacing and word-spacing properties are for spacing between letters or words. The value can be a length or normal. The line-height property sets the height of the lines in an element, such as a paragraph, without adjusting the size of the font. It can be a number (which specifies a multiple of the font size, so “2” will be two times the font size, for example), a length, a percentage, or normal. The text-align property will align the text inside an element to left, right, center, or justify. The text-indent property will indent the first line of a paragraph, for example, to a given length or percentage. This is a style traditionally used in print, but rarely in digital media such as the web.

p {
    letter-spacing: 0.5em;
    word-spacing: 2em;
    line-height: 1.5;
    text-align: center;
}

Margins and Padding

margin and padding are the two most commonly used properties for spacing-out elements. A margin is the space outside something, whereas padding is the space inside something.

Modify the CSS code for h2 to:

h2 {
    font-size: 1.5em;
    background-color: #ccc;
    margin: 25px;
    padding: 50px;
}

This leaves a 25-pixel width space around the secondary header and the header itself is fat from the 50-pixel width padding. The four sides of an element can also be set individually. margin-top, margin-right, margin-bottom, margin-left, padding-top, padding-right, padding-bottom and padding-left are the self-explanatory properties you can use.

The Box Model

You don’t have to use all of these, but it can be helpful to remember that the box model can be applied to every element on the page, and that’s a powerful thing!

Borders

Borders can be applied to most HTML elements within the body. To make a border around an element, all you need is border-style. The values can be solid, dotted, dashed, double, groove, ridge, inset and outset. border-width sets the width of the border, most commonly using pixels as a value. There are also properties for border-top-width, border-right-width, border-bottom-width and border-left-width. Finally, border-color sets the color. Add the following code to the CSS file:

h2 {
    border-style: dashed;
    border-width: 3px;
    border-left-width: 10px;
    border-right-width: 10px;
    border-color: red;
 } 

This will make a red dashed border around all HTML secondary headers (the h2 element) that is 3 pixels wide on the top and bottom and 10 pixels wide on the left and right (these having over-ridden the 3 pixel wide width of the entire border).

Positioning of elements

Element Positioning with CSS

For DHTML content developers, the most important feature of CSS is the ability to use ordinary CSS style attributes to specify the visibility, size, and precise position of individual elements of a document. In order to do DHTML programming, it is important to understand how these style attributes work. They are summarized in Table 18-2 and documented in more detail in the sections that follow.

Table 18-2. CSS positioning and visibility attributes
Attribute(s) Description
position Specifies the type of positioning applied to an element
top, left Specifies the position of the top and left edges of an element
bottom, right Specifies the position of the bottom and right edges of an element
width, height Specifies the size of an element
z-index Specifies the "stacking order" of an element relative to any overlapping elements; defines a third dimension of element positioning
display Specifies how and whether an element is displayed
visibility Specifies whether an element is visible
clip Defines a "clipping region" for an element; only portions of the element within this region are displayed
overflow Specifies what to do if an element is bigger than the space allotted for it

18.2.1. The Key to DHTML: The position Attribute

The CSS position attribute specifies the type of positioning applied to an element. The four possible values for this attribute are:

static

This is the default value and specifies that the element is positioned according to the normal flow of document content (for most Western languages, this is left to right and top to bottom.) Statically positioned elements are not DHTML elements and cannot be positioned with the top, left, and other attributes. To use DHTML positioning techniques with a document element, you must first set its position attribute to one of the other three values.

absolute

This value allows you to specify the position of an element relative to its containing element. Absolutely positioned elements are positioned independently of all other elements and are not part of the flow of statically positioned elements. An absolutely positioned element is positioned either relative to the <body> of the document or, if it is nested within another absolutely positioned element, relative to that element. This is the most commonly used positioning type for DHTML.

fixed

This value allows you to specify an element's position with respect to the browser window. Elements with fixed positioning do not scroll with the rest of the document and thus can be used to achieve frame-like effects. Like absolutely positioned elements, fixed-position elements are independent of all others and are not part of the document flow. Fixed positioning is a CSS2 feature and is not supported by fourth-generation browsers. (It is supported in Netscape 6 and IE 5 for the Macintosh, but it is not supported by IE 5 or IE 6 for Windows).

relative

When the position attribute is set to relative, an element is laid out according to the normal flow, and its position is then adjusted relative to its position in the normal flow. The space allocated for the element in the normal document flow remains allocated for it, and the elements on either side of it do not close up to fill in that space, nor are they "pushed away" from the new position of the element. Relative positioning can be useful for some static graphic design purposes, but it is not commonly used for DHTML effects.

Specifying the Position and Size of Elements

Once you have set the position attribute of an element to something other than static, you can specify the position of that element with some combination of the left top, right, and bottom attributes. The most common positioning technique is to specify the left and top attributes, which specify the distance from the left edge of the containing element (usually the document itself ) to the left edge of the element, and the distance from the top edge of the container to the top edge of the element. For example, to place an element 100 pixels from the left and 100 pixels from the top of the document, you can specify CSS styles in a style attribute as follows:

<div style="position: absolute; left: 100px; top: 100px;"> 

The containing element relative to which a dynamic element is positioned is not necessarily the same as the containing element within which the element is defined in the document source. Since dynamic elements are not part of normal element flow, their positions are not specified relative to the static container element within which they are defined. Most dynamic elements are positioned relative to the document (the <body> tag) itself. The exception is dynamic elements that are defined within other dynamic elements. In this case, the nested dynamic element is positioned relative to its nearest dynamic ancestor. Although it is most common to specify the position of the upper-left corner of an element with left and top, you can also use right and bottom to specify the position of the bottom and right edges of an element relative to the bottom and right edges of the containing element. For example, to position an element so that its bottom-right corner is at the bottom-right of the document (assuming it is not nested within another dynamic element), use the following styles:

position: absolute; right: 0px; bottom: 0px; 

To position an element so that its top edge is 10 pixels from the top of the window and its right edge is 10 pixels from the right of the window, you can use these styles:

position: fixed; right: 10px; top: 10px; 

Note that the right and bottom attributes are newer additions to the CSS standard and are not supported by fourth-generation browsers, as top and left are. In addition to the position of elements, CSS allows you to specify their size. This is most commonly done by providing values for the width and height style attributes. For example, the following HTML creates an absolutely positioned element with no content. Its width, height, and background-color attributes make it appear as a small blue square:

<div style="position: absolute; left: 10px; right: 10px;
            width: 10px; height: 10px; background-color: blue">
</div> 
 

Another way to specify the width of an element is to specify a value for both the left and right attributes. Similarly, you can specify the height of an element by specifying both top and bottom. If you specify a value for left, right, and width, however, the width attribute overrides the right attribute; if the height of an element is over-constrained, height takes priority over bottom. Remember that it is not necessary to specify the size of every dynamic element. Some elements, such as images, have an intrinsic size. Furthermore, for dynamic elements that contain text or other flowed content, it is often sufficient to specify the desired width of the element and allow the height to be determined automatically by the layout of the element's content. In the previous positioning examples, values for the position and size attributes were specified with the suffix "px". This stands for pixels. The CSS standard allows measurements to be done in a number of other units, including inches ("in"), centimeters ("cm"), points ("pt"), and ems ("em" -- a measure of the line height for the current font). Pixel units are most commonly used with DHTML programming. Note that the CSS standard requires a unit to be specified. Some browsers may assume pixels if you omit the unit specification, but you should not rely on this behavior. Instead of specifying absolute positions and sizes using the units shown above, CSS also allows you to specify the position and size of an element as a percentage of the size of the containing element. For example, the following HTML creates an empty element with a black border that is half as wide and half as high as the containing element (or the browser window) and centered within that element:

<div style="position: absolute; left: 25%; top: 25%; width: 50%; height: 50%;
            border: 2px solid black">
</div>

Element size and position details

It is important to understand some details about how the left , right, width, top, bottom, and height attributes work. First, width and height specify the size of an element's content area only; they do not include any additional space required for the element's padding, border, or margins. To determine the full onscreen size of an element with a border, you must add the left and right padding and left and right border widths to the element width, and you must add the top and bottom padding and top and bottom border widths to the element's height Since width and height specify the element content area only, you might think that left and top (and right and bottom) would be measured relative to the content area of the containing element. In fact, the CSS standard specifies that these values are measured relative to the outside edge of the containing element's padding (which is the same as the inside edge of the element's border). Let's consider an example to make this clearer. Suppose you've created a dynamically positioned container element that has 10 pixels of padding all the way around its content area and a 5 pixel border all the way around the padding. Now suppose you dynamically position a child element inside this container. If you set the left attribute of the child to "0 px", you'll discover that the child is positioned with its left edge right up against the inner edge of the container's border. With this setting, the child overlaps the container's padding, which presumably was supposed to remain empty (since that is the purpose of padding). If you want to position the child element in the upper left corner of the container's content area, you should set both the left and top attributes to "10px". Figure 18-1 helps to clarify this.

Figure 18-1

Dynamically positioned container and child elements with some CSS attributes

Now that you understand that width and height specify the size of an element's content area only and that the left, top, right, and bottom attributes are measured relative to the containing element's padding, there is one more detail you must be aware of: Internet Explorer Versions 4 through 5.5 for Windows (but not IE 5 for the Mac) implement the width and height attributes incorrectly and include an element's border and padding (but not its margins). For example, if you set the width of an element to 100 pixels and place a 10-pixel margin and a 5-pixel border on the left and right, the content area of the element ends up being only 70 pixels wide in these buggy versions of Internet Explorer. IE 6, the CSS position and size attributes work correctly when the browser is in standards mode and incorrectly (but compatibly with earlier versions) when the browser is in compatibility mode. Standards mode, and hence correct implementation of the CSS "box model," is triggered by the presence of a <!DOCTYPE> tag at the start of the document, declaring that the document adheres to the HTML 4.0 (or later) standard or some version of the XHTML standards. For example, any of the following three HTML document type declarations cause IE 6 to display documents in standards mode:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Strict//EN">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

Netscape 6 and the Mozilla browser handle the width and height attributes correctly. But these browsers also have standards and compatibility modes, just as IE does. The absence of a <!DOCTYPE> declaration puts the Netscape browser in quirks mode, in which it mimics certain (relatively minor) nonstandard layout behaviors of Netscape 4. The presence of <!DOCTYPE> causes the browser to break compatibility with Netscape 4 and correctly implement the standards.

Layer on layer with z-index (Layers)

CSS operates in three dimensions - height, width and depth. We have seen the first two dimensions in previous lessons. In this lesson, we will learn how to let different elements become layers. In short, this means the order of which the elements overlap one another.

For that purpose, you can assign each element a number (z-index). The system is that an element with a higher number overlaps an element with a lower number . Think of z-index stacking as layering. Check out the image below for an example: Let us say we are overlapping layer in order 0f 1 to 3 from bottom. Our hand can be presented in a way where each card has got a z-index:

z-index stack

In this case, the numbers follow on another (0-3) but the same result can be obtained by using 4 different numbers. The important thing is the chronological sequence of the numbers (the order). The code in the card example could look like this:

	 
	#Layer0 {
		position: absolute;
		left: 100px;
		top: 100px;
		z-index: 0;
	}

	#Layer1{
		position: absolute;
		left: 115px;
		top: 115px;
		z-index: 1;
	}

	#Laye2{
		position: absolute;
		left: 130px;
		top: 130px;
		z-index: 2;
	}

	#Layer4{
		position: absolute;
		left: 145px;
		top: 145px;
		z-index: 3;
	}
	 
	

All in One Example

The code below covers all of the CSS methods in this section. If you save this as your CSS file and observe HTML file then it should be clear what each CSS property does and how to apply them. The best way to fully understand all of this is to keep on changing property values and see the effect of each change

body {
    font-family: arial, helvetica, sans-serif;
    font-size: 14px;
    color: black;
    background-color: #ffc;
    margin: 20px;
    padding: 0;
}

/* This is just comment,*/

p {
    line-height: 21px;
}

h1 {
    color: #ffc;
    background-color: #900;
    font-size: 2em;
    margin: 0;
    margin-bottom: 7px;
    padding: 4px;
    font-style: italic;
    text-align: center;
    letter-spacing: 0.5em;
    border-bottom-style: solid;
    border-bottom-width: 0.5em;
    border-bottom-color: #c00;
}

h2 {
    color: white;
    background-color: #090;
    font-size: 1.5em;
    margin: 0;
    padding: 2px;
    padding-left: 14px;
}

h3 {
    color: #999;
    font-size: 1.25em;
}

img {
    border-style: dashed;
    border-width: 2px;
    border-color: #ccc;
}

a {
    text-decoration: none;
}

strong {
    font-style: italic;
    text-transform: uppercase;
}

li {
    color: #900;
    font-style: italic;
}

table {
    background-color: #ccc;
}

Advanced CSS

Border radius?

The border-radius property can be used to add a round corner to each corner of a box.


#marilyn {
    background: #fc0; 
    padding: 20px;
    border-radius: 10px;
}

And you get something like this. Rounded corners, see? If you’ve got a compatible browser (See list of browsers which support css3).

Or:


#ok_a_border_then {
    border: 5px solid #8b2;
    padding: 20px;
    border-radius: 5px;
}

Multiple values

border-top-left-radius, border-top-right-radius, border-bottom-right-radius, and border-bottom-left-radius can also be used to target specific corners.


#monroe {
    background: #fc0;
    padding: 20px;
    border-radius: 3px 6px 9px 12px;
}

By using two values instead of four you target top-left and bottom-right with the first length (or percentage) and top-right + bottom-left with the second. Three values? Top-left, then top-right + bottom-left, then bottom-right.

Ellipses

Are circles a bit too square for you? You can specify different horizontal and vertical radiiii by splitting values with a “/”.


#eggshape {
    width: 100px;
    height: 50px;
    text-align: center;
    padding-top: 100px;
    background: #fc0;
    border-radius: 50px/100px;
    border-bottom-left-radius: 50px;
    border-bottom-right-radius: 50px;
}

Shadows

Shadow gives shadowing effect to borders,text.. over the webpage

Box Shadows

box-shadow is the standard CSS property to get you going and it can have a value comprised of several parts:


box-shadow: 5px 5px 3px 1px #999
  1. The first value is the horizontal offset - how far the shadow is nudged to the right (or left if it’s negative)
  2. The second value is the vertical offset - how far the shadow is nudged downwards (or upwards if it’s negative)
  3. The third value is the blur radius - the higher the value the less sharp the shadow. (“0” being absolutely sharp). This is optional - omitting it is equivalent of setting “0”.
  4. The fourth value is the spread distance - the higher the value, the larger the shadow (“0” being the inherited size of the box). This is also optional - omitting it is equivalent of setting “0”.
  5. The fifth value is a color. That’s optional, too.

Inner shadows

You can also apply shadows to the inside of a box by adding “inset” to the list:


box-shadow: inset 0 0 7px 5px #ddd;

Text Shadows

box-shadow, as its name implies, only applies to. Fickle beast. But you can also apply shadows to the outline of text with text-shadow like shown below


text-shadow: -2px 2px 2px #999;

Similarly to box-shadow:

  1. The first value is the horizontal offset
  2. The second value is the vertical offset
  3. The third value is the blur radius (optional)
  4. The fourth value is the color (optional, although omitting this will make the shadow the same color as the text itself)

CSS Transitions

Transitions allow you to easily animate parts of your design without using any scripting language like javascript or Flash scripts.

Let  us assume  :hover state, where you might change the appearance of a link when a cursor fondles it:


a:link {
    color: black;
}
a:hover {
    color: gray;
}

This creates a binary animation; a link switches from black to gray when it is hovered over.

The transition property, however, is much more powerful, allowing smooth animation (rather than a jump from one state to another). It is a shorthand property that combines the following properties (which can be used individually if you so choose):

  1. transition-property: which property (or properties) will transition.
  2. transition-duration: how long the transition takes.
  3. transition-timing-function: if the transition takes place at a constant speed or if it accelerates and decelerates.
  4. transition-delay: how long to wait until the transition takes place.

Returning to the shorthand property, if a transition is applied like so…


a:link {
    transition: all .5s linear 0;
    color: hsl(36,50%,50%);
}
a:hover {
    color: hsl(36,100%,50%);
}

…when the link is hovered over, the color will gradually change rather than suddenly switch. The transition property here is saying it wants all properties transitioned over half a second in a linear fashion with no delay.

For a transition to take place, only transition-duration is required, the rest defaulting to transition-property: all; transition-timing-function: ease; transition-delay: 0;. So you could, for example, simply declare transition: .5s.

Targeting specific properties

While “all” can be used in transition-property (or transition), you can tell a browser only to transition certain properties, by simply plonking in the property name you want to change. So the previous example could actually include transition: color .5s ease 0, given only the color changes.

If you want to target more than one property (without using “all”), you can offer up a comma-separated list with transition-property:


a:link {
    transition: .5s;
    transition-property: color, font-size;
...

Or you can offer up a slew of rules for transitioning each property like so:


a:link {
    transition: color .5s, font-size 2s;
...

Easing

 

ease produces a gradual acceleration at the start of the transition and a gradual deceleration at the end. linear maintains a constant speed throughout. Other values include ease-in and ease-out.


a:link {
    -webkit-transition: .2s;
    transition: .2s;
}

The -webkit-transition property will add a transition to browsers such as Safari and older versions of Chrome, not to mention a host of mobile browsers, that don’t understand the transition property.

Transformations

Transformation is the powerful manipulation of the shape of a box and its contents using the transform property.

By default, CSS boxes, those visual representations of HTML elements, are so square. Rectangular, at least; level, with four straight sides and four boring right angles. But with the use of transform you can stretch and mold those boxes into all manner of shapes.

This page will only mention the transform and transform-origin properties but, in practice, you will probably want to duplicate these with -webkit-transform and -webkit-transform-origin to achieve the same results in the likes of Safari and Chrome as well as -ms-transform and -ms-transform-origin for Internet Explorer 9, which is the earliest version of IE that will support transforms.

Manipulating a box over two dimensions, transform can be used to rotate, skew, scale and translate a box and its contents.

Rotating

The following would result in a square orange box, all of its contents - text, images, whatever - lying flat:


.note {
    width: 300px;
    height: 300px;
    background: hsl(36,100%,50%);
}

But you can rotate it by adding a further declaration:


transform: rotate(-10deg);

This will tip the box and, importantly, everything in it, ten degrees anti-clockwise.

Skewing

Skewing allows you to tip the horizontal and vertical so the following…


transform: skew(20deg,20deg);

…will tip over the x-axis by 40 degrees on the y-axis by 10 degrees.

You can also specify one angle, such as skew(40deg), which is the equivalent of skew(40deg,0).

Scaling

Obviously, you can change width and height properties on a box, but that won’t affect the size of anything inside it. Scaling, however, will multiply not only the width and height, but the size of everything contained in the box as well:


transform: scale(2);

This will multiply the size by two. You can use any positive number, including a value less than “1”, such as “0.5”, if you want to use a shrink ray.

You can also scale the horizontal and vertical dimensions separately:


transform: scale(1,2);

This will leave the horizontal as is (because it’s a scale of 1) and multiply the vertical by two.

Translating

You can shift a box horizontally and vertically using transform: translate:


transform: translate(50px,100px);

Similar to position: relative; left: 50px; top: 100px;, this will move a box 50 pixels to the right and 100 pixels down.

As well as the values mentioned, if you want to target an individual axis, you can also use skewX, skewY, scaleX, scaleY, translateX, and translateY.

Combining transformations

Want to rotate and scale at the same time? You crazy kid. You can do this by simply separating values with spaces, such as:


transform: rotate(-10deg) scale(2);

The order of the values is important - the latter will be executed before the former. In the previous example, the box will be scaled and then rotated. It is, therefore, different to transform: scale(2) rotate(-10deg);, which will be rotated and then scaled.

Alternatively, you could use the matrix function. matrix does the whole lot - rotating, skewing, scaling, and translating. It takes six values:


transform: matrix(2,-0.35,0.35,2,0,0);

These values aren’t entirely straightforward and involve maths (or just one math if you’re of the American persuasion) that, if you really want to tackle (there are benefits not only in brevity but also in precision), it may be worth giving the specs a gander.

Origin

Assumre you are ransforming a box, there is a further parameter involved: the origin of the transformation. If you are rotating, for example, it will, by default, turn on the point that is the center of the box; if you had a piece of card, stuck a pin right through the middle of it, and then stuck that to your forehead (don’t do this), the card would spin from the middle. You can change where in the card the pin is stuck, however:


transform-origin: 0 0;

This will tell the box to transform (rotate, in the previous example) from the top left, the first “0” being horizontal, the second being vertical, like all other x-y, and you can use the usual top, right, bottom, left, length and percentage values, including negatives.

And all of that’s just with two measly dimensions. transform is a leviathan with even greater power that can also be used for three-dimensional magic. On the most basic level, you can use rotateX and rotateY, which will rotate “towards” or “away” from you on the x- and y-axis, and there are the likes of translate3d, scale3d, and the intimidating matrix3d, all of which have even greater browser difficulties than their 2D counterparts.


 

CSS3 Animation

SEE LIVE Example

What are CSS3 Animations?

The CSS animation feature was introduced into Webkit in 2007. In 2009 a working draft was written and added to the w3c site.
To use CSS animation, the most important and key concept is key-frames.you first specify some keyframes for the animation - basically what styles will the element have at certain times. The browser does the rest for you.
Animation is the process of creating motion and shape change or in real , illusion by means of the rapid display of a sequence of static images that minimally differ from each other. An animation lets an element gradually change from one style to another. If you want to achieve such motion or movement of elements on web  using css3 (rather than depending on tools like flash,silverlight..) you can define it as CSS3 animation  You can change as many CSS properties you want, as many times you want.To use CSS3 animation, you must first specify some keyframes for the animation.Keyframes hold what styles the element will have at certain times

Why CSS3 includes animation?

People who have experienced or worked with web they will definitely realize that animation was possible only by using heavy tools like flash ,silverlight..which was more about moving web experiences/website designing to software development components… In other words, we were using above mentioned tools for creating animation components which was heavy ,dependent and cumbersome experience.I don't disagree that Flash, Silver-light, AJAX, CSS – are all merely tools and all of them powerful in their own way – all of them appropriate for certain application. It is really great and very exciting that CSS3 styling language has support for Animation – Agree,we still have to wait bit to see how the standard is implemented across all browsers.
Finally leaving all religious favor-ism to tools  ,we have to agree css3 with animation is big change in web experience and will give boost to web experience

CSS3 ADVANTAGES:


There are mainly three key advantages over traditional Flash/silverlight and JS script-driven animation techniques:

  1. CSS3 Animation is declarative and easy to use for simple animations; you can create them without even having to know JavaScript.
  2. The animations run well because rendering engine can use frame-skipping and other techniques to keep the performance as smooth as possible.
  3. Giving power to browser for control the animation sequence which is surely optimized and efficient, for example, reducing the update frequency of animations running in tabs that aren't currently visible.

The Building Blocks of Animations

CSS animations are made up of two basic building blocks.

  1. Keyframes - define the stages and styles of the animation.
  2. Animation Properties - assign the @keyframes to a specific CSS element and define how it is animated.

1 )@keyframes

When you specify CSS styles inside the @keyframes rule, the animation will gradually change from the current style to the new style at certain times.To make an animation work on webpage, we must bind bind the animation to respective element like div,span,image...


Let us take simple example to understand css3 animation The following example binds the "example" animation to the <div> element. The animation will lasts for 4 seconds, and it will gradually reduce the width   of the <div> element from 100px to 10px:


SEE LIVE Example


 


After change animation-count property to infinite



<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 400px;
height: 100px;
background-color: red;
-webkit-animation-name: example; /* Chrome, Safari, Opera */
-webkit-animation-duration: 4s; /* Chrome, Safari, Opera */
animation-name: example;
animation-duration: 4s;
}

/* Chrome, Safari, Opera */
@-webkit-keyframes example {
from {width: 400px;}
to {width: 10px;}
}

/* Standard syntax */
@keyframes example {
from {width: 400px;}
to {width: 10px;}
}
</style>
</head>
<body>


<div></div>

<p><b>See:</b> When an animation is over, it will return its  original style.</p>

</body>
</html>

In the example above we have specified when the style will change by using the keywords "from" and "to" (which represents 0% (start) and 100% (complete)).



2: Animation Properties

Once the @keyframes are defined, the animation properties must be added in order for your animation to function. Animation properties do two things:

  1. They assign the @keyframes to the elements that you want to animate.
  2. They define how it is animated.

The animation properties are added to the CSS selectors (or elements) that you want to animate. You must add the following two animation properties for the animation to take effect:

  1. animation-name: The name of the animation, defined in the @keyframes.
  2. animation-duration: The duration of the animation, in seconds (e.g., 5s) or milliseconds (e.g., 200ms).

Delay an Animation

The animation-delay property specifies a delay for the start of an animation.The following example has a 3 seconds delay before starting the animation:


Example
div {
    width: 400px;
    height: 100px;
    background-color: red;
    position: relative;
    animation-name: example;
    animation-duration: 4s;
    animation-delay: 3s;
}

Set How Many Times an Animation Should Run

The animation-iteration-count property specifies the number of times an animation should run. The following example will run the animation 5 times before it stops:


Example
div {
   width: 400px;
    height: 100px;
    background-color: red;
    position: relative;
    animation-name: example;
    animation-duration: 4s;
    animation-iteration-count: 5;
}

The following example uses the value "infinite" to make the animation continue for ever:


Example
div {
   width: 400px;
    height: 100px;
    background-color: red;
    position: relative;
    animation-name: example;
    animation-duration: 4s;
    animation-iteration-count: infinite;
}

Run Animation in Reverse Direction or Alternate Cycles

The animation-direction property is used to let an animation run in reverse direction or alternate cycles.The following example will run the animation in reverse direction:

Example
div {
    width: 400px;
    height: 100px;
    background-color: red;
    position: relative;
    animation-name: example;
    animation-duration: 4s;
    animation-iteration-count: 3;
    animation-direction: reverse;
}

The following example uses the value "alternate" to make the animation first run forward, then backward, then forward:

Example
div {
    width: 400px;
    height: 100px;
    background-color: red;
    position: relative;
    animation-name: example;
    animation-duration: 4s;
    animation-iteration-count: 3;
    animation-direction: alternate;
}

Specify the Speed Curve of the Animation

The animation-timing-function property specifies the speed curve of the animation. The animation-timing-function property can have the following values:

  1. ease - specifies an animation with a slow start, then fast, then end slowly (this is default)
  2. linear - specifies an animation with the same speed from start to end
  3. ease-in - specifies an animation with a slow start
  4. ease-out - specifies an animation with a slow end
  5. ease-in-out - specifies an animation with a slow start and end
  6. cubic-bezier(n,n,n,n) - lets you define your own values in a cubic-bezier function

The following example shows the some of the different speed curves that can be used:

Example
#div1 {animation-timing-function: linear;}
#div2 {animation-timing-function: ease;}
#div3 {animation-timing-function: ease-in;}
#div4 {animation-timing-function: ease-out;}
#div5 {animation-timing-function: ease-in-out;}

How to use CSS3 animation


All in one example


The animations presented below involve setting up a transformation to take place in response to a mouseover or other event. Then, rather than applying the effect instantly, we assign a transition timing function which causes the transformation to take place incrementally over a set time period. This is all illusion what we are creating with below sprite image with all possible steps of human while walking. you can choose horse,tiger .. any sprite image and find same animation.In reality we are showing one image at once with small small delay,which make feeling like an object is walking.


 

Steps()

The steps() function controls exactly how many keyframes will render in the animation time-frame.



Complete Stunning Example


<html>
<head> 
<title>Hello this is test</title>
<style>
    .runninggirl {
        margin-left: 400px;
        width: 68px;
        height: 100px;
        background-image: url("http://www.shabirhakim.net/img/ladyrun.png");
        -webkit-animation: play .8s steps(5) infinite;
        -moz-animation: play .8s steps(5) infinite;
        -ms-animation: play .8s steps(5) infinite;
        -o-animation: play .8s steps(5) infinite;
        animation: play .8s steps(5) infinite;
    }

    @-webkit-keyframes play {
        from {
            background-position: 0px;
        }

        to {
            background-position: -500px;
        }
    }

    @-moz-keyframes play {
        from {
            background-position: 0px;
        }

        to {
            background-position: -500px;
        }
    }

    @-ms-keyframes play {
        from {
            background-position: 0px;
        }

        to {
            background-position: -500px;
        }
    }

    @-o-keyframes play {
        from {
            background-position: 0px;
        }

        to {
            background-position: -500px;
        }
    }

    @keyframes play {
        from {
            background-position: 0px;
        }

        to {
            background-position: -500px;
        }
    }
</style>
</head>

<body>
<div class="runninggirl">
</div>
</body>
</html> 

                                

SEE LIVE Example

 More Resources