Cascading Style Sheets
This is a presentation. If you'd like to view all the slides like a normal web page, you can.
Introduction to CSS
First, let's talk about what it can do when given semantic, valid markup:
What Is CSS?
- A recommendation from the W3C.
- There are currently three versions of CSS:
- A way to "style" structured documents (HTML and XML).
A Short History of CSS
- CSS as we know it today was invented by Håkon Wium Lie and Bert Bos.
- CSS1 became a recommendation in December of 1996
- CSS2 became candidate recommendation in February of 2004
- More Details
Basics
- CSS consists of selectors and declarations. For example:
h1 { color: blue }
- h1 is the selector
- everything inside { and } is the declaration.
- color is the property.
- blue is the value.
- It "selects" all h1 elements in the document, and makes their color "blue".
- We'll go into the specifics of selectors and the properties later.
Importing and Declaring Styles
There are several ways to import a style sheet into a document, or apply styles:
<link rel="stylesheet" type="text/css" href="styles.css"/>
<a href="#" style="text-decoration:none;">foo</a>
Best Practices for Importing
- The link or import methods are preferred.
- The give a better separation of content and presentation.
- Easier to manage because styles are now in one place instead of repeated all over a document.
- are easier on the user because the HTML will be smaller, and faster to download.
- We usually use the link method, and all link elements must be inside the HEAD.
Semantics, Valid Markup and Style
- The more semantic, well-formed and valid your markup, the easier it is to style.
- Give yourself usable hooks into your markup, but don't overdo it (divitis and classitis)
- Use descendant selectors to get at the children of containers.
Definitions
Semantics:
- parent: the element that contains the current element. Example: html is always the parent of body.
- child: an element that is immediately contained by another element. Example: li is always a child of a ul.
- ancestor: an element that appears more than one level above the parent, but within the same tree. Example: html is always an ancestor of p, because p is at least a child of body, which is a child of html.
- descendant: an element with within the tree of another. Example: p is always a descendant of html because p is always at least a child of body and body is always a child of html.
CSS:
- Viewport: The browser window.
- Page: The HTML document
Units
- Relative:
- em: the font-size of the relevant font, usually the width of the capital M.
- ex: the x-height of the relevant font.
- px: pixels
- Absolute:
- in: inches
- cm: centimeters
- mm: millimeters
- pt: points, only useful in print.
- pc: picas - equal to 12 points.
- And...
- zero is zero: zero pixels is the same as zero points, etc.
Selectors
- Define which elements a style applies to.
- Most common:
- type: p { color: red }
- descendant: ul li { list-style-type: square }
- pseudo-classes and pseudo-elements
- Cool, but not supported by IE:
- child: ul > li { list-style-type: square }
- adjacent sibling: li + li { color:#fff; }
- attribute: a[rel="met"] { color: #009 }
- lots more
And Now... The Pseudo's!!
- Pseudo-Classes and Pseudo-Selectors provide style options for elements in different "states" or parts of an element that aren't themselves elements.
Pseudo-Classes
The pseudo-classes in CSS 2.1 are the most widely support. There are more in 3, but no one supports them yet.
- :first-child
- Links
- :hover
- :active
- :focus
- :lang (Only Gecko supports this currently)
The Pseudo-Elements
- :first-line
- :first-letter
- :before and :after (not supported by IE)
- Pseudo-elements change to :: in CSS3.
Specificity
- The more specific style overrides the less specific one.
- The order of specificity is:
- wildcard
- element
- class
- id
- !important and style attributes
Inheritance
- If there is a selector that matches, use it.
- If not, if the property is inherited, use computed value from the parent element.
- Otherwise, use property's "initial" value, as it appears in the spec.
Common Properties That Inherit
- border-collapse and border-spacing
- color
- cursor
- direction (text direction)
- font, letter-spacing and line-height, word-spacing
- list-style
- text-align and text-indent
- white-space
The Cascade
- There is an order in which styles are applied:
- Find all styles that apply to an element and sort by importantce:
- user agent style sheets
- user normal style sheets
- author normal style sheets
- author important style sheets
- user important style sheets
- Then, they're sorted by specificity
- Lastly, sorted by order specified.
Block vs. Inline
- Block Elements:
- can have borders, margin and padding, background images, colors, break content before and after.
- Examples: p, div, ul, dl, form
- Inline Elements
- displayed inline, can't borders and don't break content before or after them.
- Examples: span, b, i, u, a, input, select
The Box Model
- Padding is inside the box.
- Margin is outside the box.
- Border is around outside of box (but inside margin)
- Outline is outside margin.
- Margin and Padding are added to the width, not included inside the specified width.
The Illustrated Box Model

When A Box Is Not A Box
- Inline elements can be made blocks by using display: block.
- Block elements can be made inline by using display: inline.
- Any element can be hidden by using display: none.
- Any element can be made to look like a list item by using display: list-item
- doesn't work in IE very well.
When An X Is Not An X
- The display property allows you to give one element the properties of another type of element.
- There are several options besides block and inline:
- none: hides the element, collapses space it would normally take up
- inherit: Inherits display properties from ancestors.
- list-item: uses the user-agent stylesheet styles for a list item.
- inline-block: creates a block element that can be styled as a block can, but displays it inline. not supported by anyone currently
- table, inline-table, table-row-group, table-header-group, table-footer-group, table-row, table-column-group, table-column, table-cell, table-caption: Turns other elements into tables. not supported by IE, most styles not supported by anyone yet
Shorthand
- CSS provides several "shorthand" properties that allow you to combine several related properties together.
- Several CSS properties support shorthand expressions: padding, margin, border, background, list-style, font, and RGB values.
- Warning: Using shorthand can cause unintended overriding (remember the font example?).
- padding and margin shorthand goes: top, right, bottom, left.
- example: padding: 10px 5px 2px 5px;
- border: applies to all four borders.
- example: border: solid 1px red;
- see also: border-top, border-right, border-bottom, and border-left.
- background example: background: #000 url('/image.gif') no-repeat fixed top left;
Shorthand Continued
- list-style: style-type position image;
- example: list-style: disc inside url('/image.gif');
- font: overrides any of the font-specific styles, so use sparingly.
- example: font: italic small-cap bold 1.2em sans, 'lucida grande', tahoma, verdana;
- RGB: #ffffff can be trimmed to #fff.
Shorthand Example
padding-top:5px;
padding-right:10px;
padding-bottom: 15px;
padding-left: 2px;
padding: 5px 10px 15px 2px;
Backgrounds
- CSS provides several options for setting the background color and/or image of an element.
- background-color sets the background color.
- background-image sets the background image.
- background-repeat sets the repeat options
- possible values: repeat, no-repeat, repeat-x and repeat-y
- background-position: allows you to position the background image within the element's area.
Background Shorthand
- You should always try to use the shorthand property for background, as it's much shorter than the individual properties.
background: #000 url("image.gif") no-repeat fixed left top
Lists
- Lists provide many, many possibilities for styling.
- You can change the "bullet" image with: list-style-image.
- You can change the bullet style with list-style-type.
- You can change how the bullet is positioned (inside or outside) with list-style-position.
- Lists are easy to style, to make them look like other elements, or implement complex design concepts.
Setting Fonts
- You can set just the family, using font-family.
- The other font-related styles are: font-weight, font-style, font-variant, font-size, line-height and color.
- You can set weight, variant, style, size and family using font shorthand.
- Using font shorthand resets everything to default if you don't specify it.
- font shorthand is:
font: font-style font-variant font-weight font-size/line-height font-family
body {
font: italic small-caps bold 76%/1 sans, "lucida grande", tahoma, verdana, sans-serif;
color:#000;
}
The Trouble With Fonts
- Pixel sizes give the greatest control and consistency across browsers and operating systems.
- But, you can't resize pixel fonts in Internet Explorer, so we have to use something else.
- But what?
Fixing Font "Issues"
- To get around the IE bug, we can use variable font sizing: ems or percentages.
- Use 76% on the body to get close to 11px.
- Use em's after that to step up and down.
- Try using font just on the body, and using the individual styles as overrides.
Aligning Text With text-align
- CSS has four values for aligning text: left, right, center and justify.
- justify formats text like it would in a newspaper, increasing letter and word spacing to try to get lines to end evenly.
- Warnings:
- text-align should never be used to align block elements
- justify can make short text blocks look "funny".
- example
More Refined Text Controls
- line-height: sets the height of a line.
- letter-spacing: sets the space between letters
- word-spacing: sets the space between words
Boxes Can Have Borders!
There are several kinds of borders - try them all!
solid
dotted (the same as dashed in IE at 1px)
dashed
double
groove
ridge
inset
Overflow
- Allows you to constrain a box without constraining its content.
- Usable Values:
- auto: will put a scroll bar on the box if content is larger than the width or height.
- hidden: will hide content that overflows the box.
- ellipsis: puts "..." after overflowing content - only works in IE.
- Valid, but unsupported in IE:
- overflow-x: value only applies to content that overflows horizontally
- overflow-y: value only applies to content that overflows vertically.
Floating and "The Flow"
- "The Flow": The order of elements as they appear in the document.
- Floating an element takes it out of the flow at the point it appears in the document.
- Floated elements have their own flow.
Getting Out Of A Float
- To get an element to "break" a float, use the "clear" style.
#foot { clear:both; }
- This will cause that element to break under any floated elements.
- clear allows for: left, right or both.
Floating Gotchas
- Internet Explorer for Windows (6.0 and below) has a bug where it doubles the margins of floated elements. This can cause a gigantic amount of frustration, but at least now you know about it.
- Floating doesn't cause boxes outside of the floated element to break outside the floated box. Only the text of those elements wraps around the floated element. The box remains where it would normally be if the floated element weren't there.
- I like to call this "islands in the stream", if only because everything in my life leads back to Kenny Rogers.
Float Example: Two Column Layout
- Requirements:
- 200px column on the left for navigation.
- Content from the main column shouldn't wrap under navigation
- Footer should always appear below the navigation.
Float Example: The Markup
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Two Columns</title>
</head>
<body>
<div id="nav">
<ul>
<li><a href="#">Main</a></li>
<li><a href="#">Archives</a></li>
<li><a href="#">News</a>
<li><a href="#">Contact</a></li>
</ul>
</div>
<div id="content">
<h1>The Content</h1>
<p>I am the content. I am full of text.
I am full of text. I am full of text. I am full of text. I am full of text.
I am full of text. I am full of text. I am full of text. I am full of text.
I am full of text. I am full of text. I am full of text. I am full of text...</p>
</div>
<div id="foot">Copyright America Online 2005</div>
</body>
</html>
Float Example: Questions
- How would you do it?
- How do you keep the text from wrapping under the menu?
- Where else could you put the navigation?
- How do you make sure the footer appears below the navigation?
Float Example: My CSS
Available here
body {
margin:0;
padding:0;
font: 77% sans, "lucida grande", tahoma, verdana, sans-serif;
color:#000;
}
#nav {
float:left;
width:200px;
}
#content {
margin:0 0 0 205px;
}
#foot {
clear:left;
}
Beyond Float: Positioning
- There are four types of positioning: static, relative, absolute and fixed.
- static: the default. The element exists in the normal flow.
- relative: the space for the elements box remains, but the element can be positioned relative to its starting position.
- absolute: element is now totally out of the flow, other elements ignore it. It is positioned relative to its containing block.
- fixed: element is out of the normal flow, but it's position is "pinned" to some reference, and in most media types, doesn't scroll. Not supported by IE.
Positioning Example: Relative - The Markup
We'll use the markup from our float example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Two Columns</title>
</head>
<body>
<div id="nav">
<ul>
<li><a href="#">Main</a></li>
<li><a href="#">Archives</a></li>
<li><a href="#">News</a>
<li><a href="#">Contact</a></li>
</ul>
</div>
<div id="content">
<h1>The Content</h1>
<p>I am the content. I am full of text.
I am full of text. I am full of text. I am full of text. I am full of text.
I am full of text. I am full of text. I am full of text. I am full of text.
I am full of text. I am full of text. I am full of text. I am full of text...</p>
</div>
<div id="foot">Copyright America Online 2005</div>
</body>
</html>
Positioning Example: Relative - Initial CSS
We'll even start with the same CSS:
body {
margin:0;
padding:0;
font: 77% sans, "lucida grande", tahoma, verdana, sans-serif;
color:#000;
}
#nav {
float:left;
width:200px;
}
#content {
margin:0 0 0 205px;
}
Positioning Example: Relative - New CSS
#content h1 {
position:relative;
top:20px;
left:5px;
padding:5px;
border:solid 1px #000;
background:#eee;
}
#content p {
padding:10px;
border:solid 1px #9cf;
background:#def;
}
Positioning Example: Relative - Explanation
- The header should now overlap the content paragraph by about 5px.
- The space where content was before we moved it is still there.
- Available here
Positioning Example: Absolute
- We'll use the same markup we had before.
- We'll start with the same style as the float example.
- We're going to move the menu to the right of the page and see what happens.
Positioning Example: Absolute - CSS Step One
body {
margin:0;
padding:0;
font: 77% sans, "lucida grande", tahoma, verdana, sans-serif;
color:#000;
}
#nav {
position:absolute;
right:0;
width:200px;
}
Positioning Example: Absolute - What's That Look Like?
Positioning Example: Absolute - CSS Step Two
body {
margin:0;
padding:0;
font: 77% sans, "lucida grande", tahoma, verdana, sans-serif;
color:#000;
}
#nav {
position:absolute;
right:0;
width:200px;
}
#content {
margin: 0 205px 0 0;
}
Positioning Example: Absolute - Explanation
- Nothing "floats" around absolutely positioned elements.
- You have to create its spot.
- Can be problematic when you aren't sure of the height of a positioned element.
- Should look like this
CSS Media Types & Profiles
- Allow CSS to be targeted to different devices with different properties/needs.
- In CSS2.1, they're called "Media Types". In CSS3, they're "Profiles".
- There is still spotty or no support for most of them. Print is the only one that's widely used.
- There are several of them:
- screen, tv and projection
- print
- handheld
- tty, speech, braille and embossed
Declaring A Media Type or Profile
- For a linked style sheet:
<link rel="stylesheet" type="text/css" href="/css.css" media="screen"/>
- For and imported style sheet:
@import url("/css.css") screen;
- For inline or inside another style sheet:
@media print {
#ad { display:none; }
}
@media print
- Allows you to specify a style sheet for printed material.
- Good way to hide non-essential elements from a printer.
- See AOL Search
- If you need a print version of a page, save you development time, because you don't need to actually create a new page, just apply a print style sheet to the existing one.
@media handheld
- Support is spotty at best.
- It's coming... The Treo 600 and 650 both support it fairly well, although they break the rules and follow screen as well.
- See my mapquest example
The Method In The Madness
- Use a compliant browser for development
- Start with content - what is it? How should I mark it up?.
- Style layout first
- After that, colors and font sizes
- "Effects"
- Check in IE
- Hacks and extra (non-semantic markup) as a last resort
- Combine styles where possible (links, for example)
Keeping Your Style Sane
- Keep styles for sections together.
- Always style HTML tags first (body, a, li, etc) in the stylesheet.
- Style ID's next, followed by classes.
- Inside declarations, try to keep styles in some sort of order:
- float and display
- width and height
- margin and padding
- borders and backgrounds
- color and font style.
Optimizing Your CSS
- Minimize whitespace
- Remove comments
- Use shorthand
- Combine styles where possible.
Hack One: The Underscore
- Putting an underscore before any style will cause it to be hidden from everyone but Internet Explorer for Windows.
- Example:
_margin: 0 0 0 0;
Hack Two: The Child Selector
- Since Internet Explorer for Windows doesn't support child selectors, it's a good way to declare styles for "good" browsers and hide things from IE.
- Example:
html>body ul { margin:0; }
The Preferred Hacks
- The underscore hack for doing IE-only styles.
- The child-selector for hiding things from IE.
- That's really it...
IE Bug: Double Margins
- On floated elements, IE doubles any specified margins.
- Avoid margins on floated elements
- Use the underscore hack to compensate.
IE Bug: Floated Elements and Comments
- This one appears off and on, but if you have floated elements with comments right after it, or inside of it, content will sometimes get "mangled".
- Solution: Remove comments.
IE Bug: Whitespace
- IE creates content blocks out of whitespace between block elements
- Causes problems with styled vertical lists.
- Only real fix at the moment is to remove the whitespace.
Extra Credit: CSS Zen Garden
- Grab the markup from the zen garden.
- Do something:
- Change the font.
- Try floating the intro div and make it look OK with the other elements.
- Do something interesting with the header.
- What can you do with the header (inside of intro)?
Zen Garden Notes
- The markup's not the best. It's a few years old, and has a lot of extra elements (spans, mostly) that I wouldn't suggest copying in your own markup.
- Try to do what you need by styling the outermost containers, and do your best to ignore the fluff (unless you want to play with it, which is fine).
- Play. Hard.
Conclusions
- Beware the IE double-margin float bug.
- Beware of specificity conflicts.
- Don't use !important.
- Start with good markup.
- Don't get frustrated. This takes time.
Questions?
- You've got to have at least one...
- No, come on.
- Anyone?
category: Presentations, CSS