Você está na página 1de 30

CSS 101

What is CSS?

Nick Foxall

CSS (Cascading Style Sheets) define how XHTML elements and markup should be displayed by the browser (or user agent). CSS can be included in the <head> area of an XHTML document, as an inline style within the content itself, or placed in external Style Sheet files. Having all styles in an external Style Sheet is preferable, because it allows for the style formatting of many pages from one file, saving a lot of updating work.

The CSS Cascade


Multiple style definitions are able to cascade into one. Styles "cascade" into a new "virtual" style sheet in the following rule order, where number four has the highest priority: 1. 2. 3. 4. Browser default External style sheet Internal style sheet (inside the <head> tag) Inline style (inside an HTML element)

This means an inline style (inside an HTML element) will have the highest priority and will override a style declared inside the <head> tag, which in turn will override a style in an external style sheet, which finally in turn overrides browser default styles. In practice, when using an external style sheet, we rarely put styles in the document <head> or inline within the content.

External Style Sheet (CSS) Files


An external Style Sheet is merely a text file saved with the extension .css. At the top of a new CSS document, the character set should be specified: @charset "UTF-8"; This is not essential, but is good practice to ensure the CSS file is compliant with web standards. A new, blank .css file created in Dreamweaver will automatically include this syntax.

CSS Rules
A CSS Style Sheet is basically a collection of rules, describing how the browser should display XHTML elements. Each rule contains 2 parts: 1. A Selector, stating which element in the XHTML a rule applies to; 2. One or more Declarations, which describe how these elements should be displayed.

h1

{ font-family: Times, Georgia, serif; font-size: 24px; text-align: center; } Declaration

Selector

A more readable way of writing CSS rules is to put each declaration on a separate line: h1 { font-family: Times, Georgia, serif; font-size: 24px;

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 1

CSS 101
text-align: center; } Each declaration consists of two parts; a property and a value: h1 { font-family: Trebuchet MS, Times, Georgia, serif; font-size: 24px; text-align: center; } Property Value

Nick Foxall

Each declaration ends with a semi-colon ; . Properties and values are separated with a colon : . All declarations must be enclosed within curly brackets { and } . Unlike XHTML, values do not have to be enclosed in quotation marks, unless the value name includes a space, such as the font-family value Trebuchet MS above.

CSS Versions
Like XML and XHTML, CSS specifications are laid down and governed by the World Wide Web Consortium. The current, most widely used version of the CSS specification is version 2.1 There are over 100 different properties available in CSS 2.1. You can view the current CSS 2.1 specification at http://www.w3.org/TR/CSS21/ .You can also validate the CSS youre working on by going to http://jigsaw.w3.org/css-validator/ and using one of the options provided to validate your CSS.

CSS Selectors Element Selectors


The simplest form of CSS selector is an XHTML element name, such as h1, h2, p, ol, ul, table, and so on. Example: p { color: #003366; } h1 { font-size: 24px; } This will set every occurrence of content marked up the <p> paragraph element to be a dark blue colour, and every occurrence of the <h1> element to the size 24 pixels.

Class Selectors
In XHTML, markup elements can have class attributes assigned to them. The value attached to a class attribute can be one (or more) names, separated by spaces, such as: <h1 class=special> The actual definition of the value special is defined in a CSS class selector: h1.special { color: #FF0000; } This will now make all h1 elements with the class special in the XHTML document display text with a red colour. h1 elements that dont have the class attribute special will continue to display in the default h1 colour (probably black, if it is not set elsewhere in the Style Sheet). A CSS class selector can also be defined

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 2

CSS 101
more generally, without the element name (just the dot): .special { color: #FF0000; }

Nick Foxall

This class can now be applied to any XHTML element that has the class attribute special. Actually the full CSS syntax is *.special, where * (asterix) is a selector that matches anything. However, CSS shorthand means we can drop the * from the front.

ID Selectors
XHTML elements can also have id selectors assigned to them, such as: <p id=summary>This is a summary of the annual general meeting.</p> In CSS, the id summary can be styled in a rule like this: #summary { font-style: italic; } id selectors are always defined with a # (number symbol) first. Again, this is CSS shorthand for: *#summary { font-style: italic; } Whats the difference between class selectors and ID selectors? Whereas class selectors can be used across a number of elements in an XHTML document, ID selectors are usually assigned to one specific element in the XHTML only.

Pseudo-classes
This is a set of special classes used to add effects to certain elements. They are used most often to style the anchor elements <a> of hyperlinks. There are four pseudo-class elements provided to make rollover and on-click effects possible: a:link { color: blue; text-decoration: underlined; } a:visited { color: green; text-decoration: underlined; } a:hover { color: red; text-decoration: none; } a:active { color: purple; text-decoration: none; } link not yet visited visited link effect on the link when the mouse hovers over it effect on the link when the mouse button is pressed down on it

Note that pseudo-classes must be written in the CSS in this order for them to work (i.e. link, visited, hover, active). Pseudo-classes can also be written without the a (anchor) class element in certain cases: :link { color: blue; text-decoration: underlined; } Pseudo-classes can also be combined with regular CSS class selectors to create multiple link and rollover styles, depending on the parent class. These examples would create different link colours, depending on which parent XHTML element had the corresponding class attribute: a.main:link { color: blue; } a.sidebar:link { color: grey; } a.footer:link { color: white; }

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 3

CSS 101
Element Selector Grouping
h1, h2, h3, h4, h5, h6 { color: #FF0000; } Each element is separated by a comma, except for the last element before the start of the declaration.

Nick Foxall

Element selectors can be grouped together if you want to apply one CSS rule to a range of elements, as in:

Class and Element Selector Order


A class selector will take precedence over a more general element selector. For example, These two CSS rules set the color of paragraph elements: p { color: #666666; } p.first { color: #000000; } The top rule sets all general <p> text content to a grey colour. The next rule sets all paragraphs with the class attribute first (i.e. <p class=first> ) to black colour text. The p.first rule takes precedence and changes the text to black. If an XHTML element belongs to more than one class, then the later CSS rules take precedence over earlier ones, for example: p.first { color: #000000; } p.changed { color: purple; } Here, a <p> element in the XHTML is specified with both classes (i.e. <p class=first changed> ) then the text will become purple, not black, because the last class rule in the order takes precedence.

Inheritance
CSS rules assigned to elements in an XHTML document are also inherited by that elements children. The value of a property is applied to the entire contents of an element. For example, note the following CSS rules: .special { color: red; } .extraspecial { color: purple; }

Then note the XHMTL markup with the class special applied to the <p> element: <p class=special>Here is some text <em>with some special emphasis </em> and continuing on.</p> The <em> tag is a child of the <p> tag, so the entire paragraph will be shown in red colour as specified in the CSS rule for .special. However, if the <em> tag is assigned a specific class, then it will take on the properties of that class, even though its still a child of <p>: <p class=special>Here is some text <em class=extraspecial>with some special emphasis </em> and continuing on.</p> Here, <em> is still a child of <p>, but it now has a class of extraspecial which will change the colour of the text inside to purple. Inheritance is useful, because we can set default values for properties in top-level elements, such as <html> and <body>, then adjust certain properties for various elements down the line.

Descendent or Contextual Selectors

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 4

Nick Foxall Descendent Selectors (sometimes called contextual) can give a finer level of control over class selectors. Examples: p em { font-weight: bold; color: red; } Bold and blue will be applied to the <em> element, only if it occurs inside a <p> element. It would not apply if the <em> was inside say an <h1> element. #mainNav ul { font-family: Arial, sans-serif } The font of the <ul> element would only change to Arial if it was inside the content area defined by the ID #mainNav Each descendent element is separated by a single space in the CSS code (no commas!)

CSS 101

Core CSS Rules


The following tables outline a core set of CSS rules most commonly used in styling XHTML web pages. Column definitions: IE, F, N: shows earliest version of CSS support in each browser, where IE = Internet Explorer, F = Firefox, N = Netscape. W3C: shows the CSS version that the rule was first defined and recommended in (CSS 1, or CSS 2). Length: The term length in the value column refers to units that may be specified in pixels, ems, cm, mm, or inches. Note that all CSS properties and values are written with American spelling (e.g. color, not colour).

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 5

CSS 101
Backgrounds
Property background Description Values IE 4 F 1

Nick Foxall

W3C 1

A shorthand property for setting background-color all background properties in one background-image background-repeat declaration background-attachment background-position Sets whether a background scroll image is fixed or scrolls with the fixed rest of the page Sets the background color of an color-rgb color-hex element color-name transparent Sets an image as the background Sets the starting position of a background image url(URL) none top left top center top right center left center center center right bottom left bottom center bottom right x% y% xpos ypos

background-attachment

background-color

background-image

background-position

background-repeat

Sets if/how a background image repeat will be repeated repeat-x repeat-y no-repeat

Borders
Property border Description A shorthand property for setting all of the properties for the four borders in one declaration Values border-width border-style border-color IE 4 F 1 W3C 1

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 6

CSS 101
border-bottom A shorthand property for setting border-bottom-width border-style all of the properties for the bottom border in one declaration border-color Sets the color of the bottom border Sets the style of the bottom border Sets the width of the bottom border border-color 4 1

Nick Foxall 1

border-bottom-color

border-bottom-style

border-style

border-bottom-width

thin medium thick length color

border-color

Sets the color of the four borders, can have from one to four colors A shorthand property for setting all of the properties for the left border in one declaration Sets the color of the left border Sets the style of the left border Sets the width of the left border

border-left

border-left-width border-style border-color border-color border-style thin medium thick length border-right-width border-style border-color

border-left-color border-left-style border-left-width

4 4 4

1 1 1

2 2 1

border-right

A shorthand property for setting all of the properties for the right border in one declaration

border-right-color border-right-style border-right-width

Sets the color of the right border border-color Sets the style of the right border border-style Sets the width of the right border thin medium thick length none hidden dotted dashed solid

4 4 4

1 1 1

2 2 1

border-style

Sets the style of the four borders, can have from one to four styles

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 7

CSS 101
double groove ridge inset outset border-top A shorthand property for setting all of the properties for the top border in one declaration Sets the color of the top border Sets the style of the top border Sets the width of the top border border-top-width border-style border-color border-color border-style thin medium thick length thin medium thick length 4 1

Nick Foxall

border-top-color border-top-style border-top-width

4 4 4

1 1 1

2 2 1

border-width

A shorthand property for setting the width of the four borders in one declaration, can have from one to four values

Classification
Property clear Description Sets the sides of an element where other floating elements are not allowed Values left right both none url auto crosshair default pointer move e-resize ne-resize nw-resize n-resize se-resize sw-resize s-resize w-resize IE 4 F 1 W3C 1

cursor

Specifies the type of cursor to be displayed

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 8

CSS 101
text wait help display Sets how/if an element is displayed none inline block list-item run-in compact marker table inline-table table-row-group table-header-group table-footer-group table-row table-column-group table-column table-cell table-caption left right none static relative absolute fixed visible hidden collapse 4 1

Nick Foxall

float

Sets where an image or a text will appear in another element

position

Places an element in a static, relative, absolute or fixed position

visibility

Sets if an element should be visible or invisible

Dimensions
Property height Description Sets the height of an element Values auto length % IE 4 F 1 W3C 1

line-height

Sets the distance between lines normal number length %

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 9

CSS 101
max-height Sets the maximum height of an element none length % none length % length % length % auto % length 1

Nick Foxall 2

max-width

Sets the maximum width of an element

min-height

Sets the minimum height of an element Sets the minimum width of an element Sets the width of an element

min-width

width

Text
Property color direction Description Sets the color of a text Sets the text direction Values color ltr rtl IE 3 6 F 1 1 W3C 1 2

line-height

Sets the distance between lines normal number length % Increase or decrease the space between characters Aligns the text in an element normal length left right center justify none underline overline line-through blink

letter-spacing

text-align

text-decoration

Adds decoration to text

text-indent

Indents the first line of text in an length % element

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 10

CSS 101
text-transform Controls the letters in an element none capitalize uppercase lowercase normal pre nowrap normal length 4 1

Nick Foxall 1

white-space

Sets how white space inside an element is handled

word-spacing

Increase or decrease the space between words

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 11

CSS 101
Fonts
Property font Description A shorthand property for setting all of the properties for a font in one declaration Values font-style font-variant font-weight font-size/line-height font-family caption icon menu message-box small-caption status-bar family-name generic-family IE 4 F 1

Nick Foxall

W3C 1

font-family

A prioritized list of font family names and/or generic family names for an element Sets the size of a font

font-size

xx-small x-small small medium large x-large xx-large smaller larger length %

font-size-adjust

Specifies an aspect value for an none element that will preserve the x- number height of the first-choice font Condenses or expands the current font-family
normal wider narrower ultra-condensed extra-condensed condensed semi-condensed semi-expanded expanded extra-expanded ultra-expanded

font-stretch

font-style

Sets the style of the font

normal

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 12

CSS 101
italic oblique font-variant Displays text in a small-caps font or a normal font Sets the weight of a font normal small-caps
normal bold bolder lighter 100 200 300 400 500 600 700 800 900

Nick Foxall

font-weight

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 13

CSS 101
Margins
Property margin Description A shorthand property for setting the margin properties in one declaration Values margin-top margin-right margin-bottom margin-left auto length % auto length % auto length % auto length % IE 4 F 1

Nick Foxall

W3C 1

margin-bottom

Sets the bottom margin of an element

margin-left

Sets the left margin of an element

margin-right

Sets the right margin of an element

margin-top

Sets the top margin of an element

Padding
Property padding Description A shorthand property for setting all of the padding properties in one declaration Values padding-top padding-right padding-bottom padding-left length % length % length % length % IE 4 F 1 W3C 1

padding-bottom

Sets the bottom padding of an element Sets the left padding of an element Sets the right padding of an element Sets the top padding of an element

padding-left

padding-right

padding-top

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 14

CSS 101
Positioning
Property bottom Description Values IE 5 F 1

Nick Foxall

W3C 2

Sets how far the bottom edge of auto % an element is above/below the length bottom edge of the parent element Sets the shape of an element. The element is clipped into this shape, and displayed Sets how far the left edge of an element is to the right/left of the left edge of the parent element Sets what happens if the content of an element overflow its area shape auto

clip

left

auto % length visible hidden scroll auto static relative absolute fixed auto % length

overflow

position

Places an element in a static, relative, absolute or fixed position

right

Sets how far the right edge of an element is to the left/right of the right edge of the parent element Sets how far the top edge of an element is above/below the top edge of the parent element

top

auto % length

vertical-align

Sets the vertical alignment of an baseline element sub super top text-top middle bottom text-bottom length % Sets the stack order of an element auto number

z-index

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 15

CSS 101
Tables
Property border-collapse Description Sets whether the table borders are collapsed into a single border or detached as in standard HTML Values collapse separate IE 5 F 1

Nick Foxall

W3C 2

border-spacing

Sets the distance that separates length length cell borders (only for the "separated borders" model) Sets the position of the table caption top bottom left right show hide

5M

caption-side

5M

empty-cells

Sets whether or not to show empty cells in a table (only for the "separated borders" model)

5M

table-layout

Sets the algorithm used to auto display the table cells, rows, and fixed columns

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 16

CSS 101
Pseudo-Classes
Pseudo-class :active :focus Purpose Adds special style to an activated element Adds special style to an element while the element has focus Adds special style to an element when you mouse over it Adds special style to an unvisited link Adds special style to a visited link Adds special style to an element that is the first child of some other element Allows the author to specify a language to use in a specified element IE 4 F 1

Nick Foxall

W3C 1

1.5 2

:hover :link :visited :first-child

4 3 3 -

1 1 1 1

1 1 1 2

:lang

Pseudo-Elements
Pseudo-element :first-letter :first-line :before :after Purpose Adds special style to the first letter of a text Adds special style to the first line of a text Inserts some content before an element Inserts some content after an element IE 5 5 F 1 1 W3C 1 1

1.5 2 1.5 2

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 17

CSS 101
CSS Layout

Nick Foxall

The 3 core concepts to understand about CSS layout are the CSS box model, Floating, and Positioning. Together, these 3 concepts control the way elements are arranged and displayed on a page. Every block element in CSS is effectively inside a box, and every block element can have margins, padding and borders applied to it. Box widths can be specified in absolute or measurable values (e.g. px, cm, etc.) or in relative values, usually: em - width values relative to the size of a font, in ems percentage - width values relative the containing boxs content region The root (or top-most) elements containing box is effectively the browser window.

The CSS Box Model


Every CSS box is divided into regions, consisting of: 1. 2. 3. 4. Content Padding Border Margins Margin Border Padding

With margin, border and padding, the properties of each of the 4 sides can be specified independently. Margins and Padding may seem similar at first glance, but each has its own effect on content, particularly on any backgrounds assigned to block and div elements. Content

Margins Margins define the space around elements outside the border. Margin properties can have negative values in order to deliberately overlap content. Margin properties will also have an affect on the position of background elements (graphics and/or colours) placed behind content. The position of background elements in particular can be changed in relation to the edges of the containing block element. Margin properties can be defined independently on top, right, bottom and left, or all-at-once using CSS shorthand.

Padding Padding defines the space around elements inside the border; i.e between the border and the content itself. Unlike

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 18

CSS 101
margins, padding properties cannot have negative values applied to them.

Nick Foxall

Also unlike margins, padding properties do not affect the position of background elements (graphics and/or colours) in the containing block element; only the position of the content itself within the containing block. Padding properties can be defined independently on top, right, bottom and left, or all-at-once using CSS shorthand.

Margin Collapse Margin collapse happens between CSS block or boxes in a stack. When 2 or more vertical margins meet, they will collapse to form a single margin. The height of this combined margin will be equal the height of the larger of the 2 margins. Margin collapse applies when: 2 or more block elements are stacked one above the other, Or when one block element is contained within another block element

This diagram shows margin collapse between stacked elements:

Before

After

Content Area

Content Area

Margin-bottom: 30px Margin-top: 20px

Margins collapse to form a single margin

Margin-bottom: 30px

Content Area Content Area

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 19

CSS 101
This diagram shows margin collapse within contained elements:
Before Margin-top: 30px Margin-top: 20px Content Area Margins collapse to form a single margin After Margin-top: 30px

Nick Foxall

Content Area

Inner block element Containing (outer) block element

* Note: only applies if there are no borders or padding separating the margins.

Borders Borders can be applied to any block element. Borders always come outside the padding area, but inside the margin area. Border properties cannot have negative values. If a border is not specified, the default is no-border (i.e. no border appears and no space between any margin and padding is allocated for a border). Just like margin and padding, border properties can be defined independently on top, right, bottom and left, or all-at-once using CSS shorthand. The core border properties are: Width: (as in thickness of line) can be absolute (px, in, cm, or thin, medium, thick), or relative (ems) Style: (as in border style) can be dotted, dashed, solid, double, groove, ridge, inset, outset, hidden, etc. [see above table for full list of border style values] Color: blue, red, #FF9900, etc

You can also create the effect of a border by using a graphic image in a CSS background property, instead of the border property.

CSS Shorthand
For many CSS properties, and particularly for margin and padding properties, CSS provides a number of shorthand ways of defining those properties that can save on writing lines and lines of code. This is an example for all 4 sides of a CSS box: #container { padding: 20px 10px 30px 12px; margin: 0 5px 6px 5px; } Note the sequence of values is always written in a clockwise order, starting from the top, so in the case of the padding here, 20px is the top padding, 10px is the right side padding, 30px is the bottom padding, and finally

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 20

Nick Foxall 12px is the left side padding. This diagram shows the order of the margin and padding defined above: You can apply just one value in the shorthand, for example: #container { padding: 20px; margin: 5px; }

CSS 101

20

QuickTime and a decompressor are needed to see this picture.

QuickTime and a decompressor are needed to see this picture.

This will apply the value specified equally on all 4 sides of the CSS box, thus:

Content Area
5 20

QuickTime and a decompressor are needed to see this picture.

12

10

30 6 Content Area
20 20

20 5
You can also apply two values in the shorthand, for example: #container { padding: 10px 20px; margin: 0px 5px; } The first value is applied to the top and bottom of the box. The second value is applied to the left and right (left diagram below):

0 10

0 10

Content Area 20 20

auto

Content Area 20 20

auto

XHTML 101: A Basic Guide 10Cascading Style Sheets | Oct 2007 to

10

Page 21

Nick Foxall A useful value to remember, no matter whether you use 1-value, 2-value, or 4-value shorthand, is the value auto. Usually applied to the left & right areas of the margin property, auto is useful for centering a block container element in the browser window. An overall block container element can be specified, which is then used to center your entire page design horizontally in the browser window. The CSS code sets the top and bottom margins to 0 (zero) and the left and right margins to auto (right diagram above): #container { padding: 10px 20px; margin: 0px auto; }

CSS 101

CSS Floats
CSS boxes for block elements within (X)HTML are stacked one above the other, so that theyre read from top to bottom. In CSS, this is said to be the normal flow, because it merely replicates the normal sequence of the content as its written in the HTML document. But using the CSS float property, we can position block element boxes side-by-side in the HTML layout. Setting the float property to left or right causes a box to be taken out of its position in the normal flow and moved as far left or right as possible. The Float property has three value options: float: left; float: right; float: none; The Normal flow of a document. Block elements are stacked one above the other (or side-by-side if space allows):

C
Floated blocks, where blocks A and B are floated left and right respectively:

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 22

CSS 101
text text text text textinlinetext text text text text text text text text text text text text text text text text text text text text text text text text text textinlinetext text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text textinlinetext text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text

Nick Foxall

block

block

To restore the normal flow, we use the CSS clear property. In the diagram above, block C has the clear property applied, which begins at the top of the cleared block element (shown by the arrows). The clear property has three value options: clear: left; clear: right; clear: both; These specify which side of the elements box may not have a float next to it. Note that in all the examples above, CSS boxes for inline elements are placed next to each other, inside boxes for block elements, and will normally wrap according to the width of the containing block.

CSS Positioning
The third core concept to understand in CSS layout (after the box model and floats), is positioning. There are two types of positioning that can be applied to CSS boxes. These are Relative Positioning, and Absolute Positioning. Understanding the differences between the two is difficult at first, but important!

Relative Positioning
A relatively positioned element will stay exactly where it is, in relation to the normal flow. You can then offset its position relative to its starting point in the normal flow.

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 23

CSS 101

Nick Foxall

Box 1

Box 2

Box 3

Containing box

top: 20px

Left: 20px

Box 1

Position: relative Box 2

Box 3

In this example, box 2 is offset 20px, top and left. The result is the box is offset 20px from its original position in the normal flow. Box 2 may overlap other boxes in the flow, but other boxes still recognise its original position in the flow. #myBox { position: relative; left: 20px; top: 20px; }

Containing box

Absolute Positioning

An absolutely positioned box is taken out of the normal flow, and positioned in relation to its nearest positioned ancestor (i.e. its containing box). If there is no ancestor box, it will be positioned in relation to the initial containing block, usually the browser window. An absolutely positioned box can be offset from its initial position inside the containing block, but other boxes within the block (and still within the normal flow) act as if the box wasnt there. This is what happens to box 2 if it is absolutely positioned:
top: 20px

Left: 20px

Box 1

Position: absolute Box 2

Box 3

Box 2 is offset 20px, top and left. The result is the box is offset 20px from its the top left corner of its containing block (or ancestor element). Box 2 may overlap other boxes in the flow, and other boxes act as if it wasnt there. #myBox { position: absolute; left: 20px; top: 20px; }

Containing box (relatively positioned ancestor)

Fixed Positioning
Fixed Positioning is a sub-category of Absolute Positioning. It allows the creation of floating elements that are always fixed in the same position in the browser window, while the rest of the content scrolls as normal (rather like the effect of fixed background attachments). Theres a problem though: fixed positioning is not supported in IE5 and IE6. It only really works in Firefox, Safari and other standards-compliant browsers, but can be made to work by using JavaScript in IE.

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 24

CSS 101
Positioning Summary

Nick Foxall

Floats (which are actually also a form of positioning) take boxes out of the normal flow and float them left or right edges of the containing block. Relative Positioning is relative to the elements initial position in the normal flow. Absolute Positioning is relative to the nearest positioned ancestor, or (if one doesnt exist) the initial container block (usually the browser window). Fixed Positioning is fixed in one position relative to the browser window only does not scroll with content (not supported in IE5, IE6).

Background Images in CSS


It is also possible to use the background CSS property with any block element (including divs) to place a background image (GIF, JPG or PNG) behind other elements. Background images can be small images that repeat horizontally or vertically (using the repeat, repeat-x, or repeat-y properties) to fill a flexible background space, or one single image that fills a space of fixed size. Background images are useful in allowing us to visually define a page, and separate content into a deliberate visual hierarchy. The ability to repeat images in a background box, and reuse the SAME images across a number of boxes, means we can make very efficient use of images. Wherever possible, background images should be used in conjunction with background colours to save on download overhead. One useful application for background images is in creating rounded corner boxes.

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 25

CSS 101
Rounded Corner Boxes

Nick Foxall

Rounded corner boxes are very popular in many site designs for defining sidebar elements, containing secondary content or sublinks, and so on. Unfortunately, the current version of CSS does not have any properties that can define rounded corners (CSS 3 will allow for the specification of a corner radius). However, rounded corner boxes are very easy to create in CSS 2 with a couple of background images.

boxtop.gif

boxshadedtop.gif

boxshadedback.gif

boxbottom.gif

boxshadedbottom.gif

A simple flat-colour, fixed-width box requires only A shaded- or graduated-colour, fixed-width box 2 images. This box has flexible vertical height. requires only 3 images, with the centre image set to repeat vertically. This box has flexible vertical height. boxshadedtopleft .gif boxshadedtopright .gif

boxshadedbottomleft .gif boxshadedbottomright .gif For a more complex shaded box that can accommodate flexible width and flexible height, you need 4 images for your box, with the lower images large enough to cover the maximum estimated size that your box will be. The CSS code for these boxes is available on the course website at http://sweb.cityu.edu.hk/SM5312/

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 26

CSS 101
Fixed Position Background Images

Nick Foxall

Background images will normally scroll with the containing box, and the rest of the page. But they can also be fixed, staying in the same position in the layout, while the rest of the content scrolls. Example: #sidebar { width: 300px; background-image: url(images/harbour.jpg); background-attachment: fixed; }

Centering Blocks in the Browser Window


Most designers like to centre their page designs horizontally in the browser window, so they layout always floats in the middle, not matter how wide the users screen. This is easily done by: 1. Setting the body element to text-align: center 2. Creating a container div (fixed or relative width), with left and right margins set to auto We can also center a container block vertically in the browser window, by: 1. Setting the body element to text-align: center 2. Creating a container div (fixed or relative width), with these CSS properties: Position: absolute; top: 50%; left: 50%; margin-top: -300px; margin-left: -400px; Note, the box must have a height specified, as well as a width for this to work, and the height must be a measured or absolute unit (i.e. px, mm, cm, etc.). You would think that setting the top and bottom margins to auto would achieve the same result as horizontal centering, but this does not work in most browsers!

The DIV Element


Weve seen that CSS box model attributes can be applied to any simple XHTML block element (p, h1, h2, etc.). However, we often use specific <div> elements within the XHTML, each identified with an ID or class name, because there are simply not enough simple (X)HTML elements to go around. We can then apply width, float, margin, padding and border properties to those divs in CSS. This gives us more options to create and control a range of layout elements, on top of the core content elements, so you find yourself making good use of divs. We can also use descendent selectors (see page 4 above), such as #container p or .sidebar h2 to apply different styles to simple elements, depending on their place in the layout (and their position within containing blocks).

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 27

CSS 101
CSS Menus and Navigation Bars

Nick Foxall

The main menu or main navigation bar is a core element of any web site design. Creating a clear and recognisable visual style for a navigation bar is important for a user-friendly site. The two most common ways to display navigation bars these days are: 1. Vertically 2. Horizontally Vertical navbars can take the form of buttons or small panels, or even plain text links with a simple border. Horizontal navbars can take the form of buttons or tabs, like these examples:

Navigation Bars in XHTML


Creating a Navigation Bar in HTML is easy. Its just a simple <ul> unordered list, with each <li> element containing the name of the section, and enclosed in a hypertext link <a href> element. <div id=navbar> <ul> <li><a href="#">Home</a></li> <li><a href="#">Products</a></li> <li><a href="#">Services</a></li> <li><a href="#">About Us</a></li> <li><a href="#">Contact Us</a></li> </ul> </div> It is also a good idea to wrap your navigation list in a div element with a specific ID name. Wrapping the unordered list in a div allows us to apply specific styling to the ul, li, and a:link sub-elements without affecting the rest of the page styling.

Navigation Bars in CSS


Images With the basic XHTML <ul> list in place, we can set about styling the list into a well-defined navigation bar. A lot can be done with just simple CSS styling using borders and background colours. However, we can also use images for a more button-like, or tab-like look and feel. For a simple rollover button effect, we only need 1 image:

We can combine the off state and the on state (or rollover state) in one image, and then use CSS background

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 28

CSS 101

Nick Foxall

positioning to shift the image to the left or right, depending on the action of the mouse triggering the a:link (off state), or the a:hover (on state). Unlike javascript-enabled buttons, we dont need to put any text in our button images. The text comes directly from text in the <ul> list in the XHTML. For a tab effect, we can use 2 images: one image for the selected or front-most tab, and one image with some bottom shading for the unselected or recessed tabs. It is also possible to use the single image format for tabs too, depending on tab spacing and how you want your tabs to look. Tab button examples:

CSS Properties For the ul element, we simply set the margins and padding to 0, and set the list-style-type to none. This turns off all bullet and indent styling. We can also set a specific width for the ul element (say 800 pixels), or use a relative value (say 100% if we want the navbar to run right across the width of the containing element). A numeric width is preferable for buttons with set-width background images. If your background button image is 200px wide, and you have 5 main buttons, then your ul width needs to be 1000px. We then apply most of the styling to the ul a element (the descendent selector of ul; the a element inside the ul element): #navbar ul a { display: block; width: 200px; height: 40px; line-height: 40px; background: #CCCCCC url(images/menubase_1.png) no-repeat left bottom; text-align: center; } display: block; Forces an inline element to act like a block element, making the whole button effectively live when moused-over

width: XXpx; height: YYpx; Fixed width and height to match dimensions of image line-height: YYpx Forces text to vertically align centre (same value as height) background: Loads the button image in the background of the block and tells it to align with left and bottom edges text-align: center; aligns the button text horizontally, giving even margins left and right inside the button/tab area The rule set above will produce a vertical navigation panel, with each button one on top of the other. To create a horizontal navigation bar, we can either change the display property to inline (from block), or tell the <li> elements to float left, with a descendent selector like this: #navbar ul li { float: left; }

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 29

CSS 101

Nick Foxall

This second property is preferable, because the display: inline; property is not reliable and can produce unexpected results in some browsers.

Button Hover / MouseOver Effects The hover or mouseover effect is applied to the a:hover property, as a descendent selector of #navbar: #navbar a:hover { color: #FFFFFF; text-decoration: underline; background-position: right bottom; } The key property here is background-position. Notice in the default state (under #navbar ul a above) the position is left bottom. Changing the position to right bottom forces the image to align to the right edge of the block element, thereby exposing the dark blue or highlighted section of the button graphic.

XHTML 101: A Basic Guide to Cascading Style Sheets | Oct 2007

Page 30

Você também pode gostar