CSS Pocket Guide PDF
CSS Pocket Guide PDF
PocketGuide
Chris Casciano
Thanks to my family, including Mom, Dad, Mari and Justin, Joanna and
Jared (and Lily), and Matt, for everything.
Finally, thanks to the people Ive shared the Internet with over the past
15 yearswhether through online communities from webdesign-l to
b3s or my co-workers and those in the NYC tech community. You shaped
my understanding of our industry and the technologies we use, and you
encouraged me to keep on keepin on throughout my career and my life.
Contents
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
Who Should Read This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi
What You Will Learn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi
What You Wont Find in This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
What You Need to Follow Along . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xviii
Writing CSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xviii
Case Sensitivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xviii
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix
Whitespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix
Quoting and Escaping Quotes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix
Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xx
Chapter 3: Selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
E (Type Selectors) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
* (Universal Selector) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Attribute Selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
[att] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
[att=val] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
[att~=val] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
[att|=val] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
[att^=val] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
[att$=val] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
[att*=val] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Pseudo-class Selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
:link, :visited (Link Pseudo-classes) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
:hover, :active, :focus (Action Pseudo-classes) . . . . . . . . . . . . . . . . . 41
:target (Target Pseudo-class) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
:enabled, :disabled, :checked (UI Pseudo-classes) . . . . . . . . . . . . . . . 42
:lang() (Language Pseudo-class) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
:root (Root Element Pseudo-class) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
:nth-child(), :nth-last-child() (Nth Child Pseudo-classes) . . . 43
:first-child, :last-child (First and Last Child Pseudo-classes) . . 44
:nth-of-type(), :nth-last-of-type() (Nth of Type Pseudo-
classes) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
:first-of-type, :last-of-type (First and Last of Type Pseudo-
classes) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
:only-child (Only Child Pseudo-class) . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
:only-of-type (Only of Type Pseudo-class) . . . . . . . . . . . . . . . . . . . . . . 46
:empty (Empty Pseudo-class) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
:not() (Negation Pseudo-class) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
viii The CSS Pocket Guide
Pseudo-element Selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
::first-letter (First-Letter Pseudo-element) . . . . . . . . . . . . . . . . . . . 47
::first-line (First-Line Pseudo-element) . . . . . . . . . . . . . . . . . . . . . . . 47
::before, ::after (Before and After Pseudo-elements) . . . . . . . . . . 47
::selection (Selection) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Basic Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
#rrggbb or #rgb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
rgb(r,g,b) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
hsl(h,s,l) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Color Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Color with Alpha Transparency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
rgba(r,g,b,a) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
hsla(h,s,l,a) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
transparent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Position . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
static . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
relative . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
absolute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
fixed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
visibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
float . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
clear . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
Introduction
The styling of web documents has evolved a great deal from the early
days of the Web when font tags, tables, and HTML attributes scattered
everywhere were just what you had to do to make pages look good (or
get that animated GIF of a ame repeating across your whole page).
The CSS Pocket Guide will teach you the building blocks of styling docu-
ments with CSS, give you an arsenal of modern development techniques,
and help you navigate the ever-changing landscape of web browsers and
specications, including CSS3.
xvi The CSS Pocket Guide
Along the way, there is also discussion of current best practices in web
development and information on upcoming changes to CSS included in
CSS3 and beyond.
Introduction xvii
The gures used to demonstrated CSS code throughout this button were
all generated with actual CSS code. These full code examples, including the
HTML5 documents, can be downloaded from http://www.peachpit.com/
csspocketguide so you can follow along, review the examples in different
browsers, or edit the examples and experiment with them.
xviii The CSS Pocket Guide
Resources
It goes without saying that a topic at the core of web development will
have a large number of great resources on the Web.
Check out the W3Cs CSS Working Groups Current Work index of the
CSS specications. http://www.w3.org/Style/CSS/current-work
You can also refer to the detailed browser support charts and other
web development articles by Peter-Paul Koch at QuirksMode.org.
http://quirksmode.org/
The WaSP InterAct Curriculum project offers a full and ongoing curric-
ulum for learning and teaching web development and web design
including CSS. http://interact.webstandards.org/
The Mozilla Developer Center offers a complete reference of the
CSS language and is great for looking things up in a ash.
https://developer.mozilla.org/en/CSS_Reference
The Opera Developer Network offers articles, tutorials, and references
for all areas of web development, including a curriculum you can walk
through and teach yourself. http://dev.opera.com/
Writing CSS
Unlike a programming language such as JavaScript, there isnt that much
to the syntax of CSS and the makeup of CSS rules. But the following
sections highlight some things you should know before jumping into the
complexities of what the simple syntax can do.
Case Sensitivity
CSS is case insensitive. For example, the color property is equivalent
to the COLOR property, and a px unit is the same as a PX or Px unit. By
Introduction xix
Parts of the code not under the control of CSS such as le paths to style
sheet documents, images, element names, classes, and IDs may be case
sensitive and are dened at their source. For example, the le path on
one server may be case sensitive, but on another server or your local
machine it may not be. For markup, elements in HTML documents are
case insensitive; however, elements in XML-based documents are.
To avoid confusion or code bugs, it is best to match the case in your code
regardless of whether it will be enforced.
Comments
There is only one way to write a comment in CSSbeginning with the
two characters /* and ending with the same two characters reversed, */.
Any text, code, or whitespace between those two is ignored.
/* this is a comment */
Whitespace
In CSS, whitespaceincluding space characters, tabs, and line breakshas
no meaning outside of its use as a descendent selector (Chapter 3) or as a
separator for multiple values in a single declaration. Outside of those two
cases, it is considered optional. It is up to you to use whitespace (or not) to
format your CSS to help with the organization and readability of your code.
appear as part of the string). The backslash character can also be used to
include characters via their character codes.
Keywords, such as color names, are not strings and must not be quoted.
Tools
Building web pages while wrangling browser bugs takes more than just
a text editor and a browser. The following are a few categories of tools
that are invaluable additions to your toolbox.
Validation Tools
Validation tools parse your HTML or CSS documents checking for
conformance with the designated specication in areas such as syntax
errors, missing or improperly nested HTML tags, unknown CSS proper-
ties, illegal values, or other coding problems. The W3C validation service
(http://jigsaw.w3.org/css-validator/ ) is one commonly used validator.
As a tool, the errors a validation service can uncover may help identify
where visual bugs youre seeing in browsers could derive from. For exam-
ple, it is common that a missing closing tag may cause styles to bleed out
of the area you would have expected. But be careful and understand vali-
dation errors before reacting to them because some code that you want
to use, such as vendor extensions for experimental CSS3 implementa-
tions, may also be reported as an error based on the validators settings.
Web Inspectors
Web inspectors (or DOM inspectors) are tools that allow you to view the
document tree, CSS properties, and other information about a web page
Introduction xxi
(I take some pride in this tool as it is based on the toolbar I had writ-
ten for the now long defunct Mozilla Suite, the browser that predated
Firefox. That said, Chris deserves all the credit now because he has taken
it further and supported it with much more time and energy than I had.)
Through YSlow and its companion suite of tool, you can learn about tools
to compress CSS documents; optimize server calls for CSS les, JavaScript
les, and images; and perform lots of other performance tricks not
covered directly in this book.
CSS Basics
HTML provides the content and structure of the web page, JavaScript
supplies the interaction and document manipulation, and CSS provides
the presentation and air.
2 The CSS Pocket Guide
What Is CSS?
CSS, short for Cascading Style Sheets, is a language for describing the
presentational properties of content elements in structured documents
such as HTML documents. Though this book will focus on styling HTML
content, you can also use CSS for other structured documents such as
those created with XML or SVG.
As a browser or other user agent loads the HTML content for the docu-
ment, it also loads the style sheet information. From this style sheet
information, it then builds up the set of presentation rules for each
individual content item based on its element type, its state, and its loca-
tion in the document. It will ultimately render each element consistently
based on this accumulated set of rules.
Anatomy of a Statement
CSS-based style sheets consist of a list of statements. There are two types
of statements: rule sets (referred to as rules) and at-rules.
Chapter 1: CSS Basics 3
Rule Sets
A rule set consists of a selector followed by a declaration block contain-
ing declarations of style properties and their values, as explained in the
following list (see also Figure 1.1).
Figure 1.1
The parts of 2
a rule set.
1
4
3
5 6
1. Rule set: This is the entire denition of a CSS rule, including selector
and declaration block, containing individual declarations.
3. Declaration block: The declaration block starts with the left curly brace
and ends with the right curly brace. Inside the block there are zero or
more declarations, each separated by a semicolon (;).
6. Value: This is the value that will be applied to the declared property.
The syntax of the value depends on the property but can be things
such as keywords, a <length>, a <percentage>, or a mix of multiple,
space-separated types.
4 The CSS Pocket Guide
At-Rules
At-rules are statements that begin with the character for at (@), followed
by a rule type or identier, and end with a semicolon. Unlike rule sets,
at-rules do not contain declarations directly but offer additional context
or commands for the processing of style sheet information. Heres an
example:
@media print {
[...]
}
Cascading
The cascading in CSS is the process that is followed in order to determine
which declaration for a given property is applied to a given element in
the document. As youll soon learn, propertiescolor, for instancecan
be dened and redened multiple times, so the browser must determine
which of those denitions to apply. The criteria for sorting through the
style sheets to determine which property declaration to use is threefold:
weight, specicity, and order of appearance.
note You can learn more about the sources of styling rules in Chapter 2.
Figure 1.2 shows the cascade of rules for a link in the footer of the
Apple.com home page as viewed in the Safari Web Inspector. Declarations
that appear crossed out have been trumped by other declarations of that
property higher in the cascading order.
Figure 1.2
The Safari
Web Inspector
displaying the
cascade.
Chapter 1: CSS Basics 7
Inheritance
The values for some properties, such as color and font-family, are
inherited by child elements of the element where the property was set. If
that property was not explicitly declared for the child element, it will use
the inherited value for display. In the case of color, if the <body> element
has been set to black, then paragraphs, list contents, block quotes, and
other children will also have a color value of black. Because links have a
different color dened in the user agent style sheet, they will not appear
as black but as the default blue color (or other set default link color).
In the previous code example, the font-size for the <strong> element
is calculated to be 20px, and this is the value inherited by the <span>
element. If the specied value of 2em was inherited and the size recal-
culated, the <span> would have a font-sized value of 40px instead. Ill
further explain computed values in the next section.
Other properties, such as width, height, and margin, are not inherited
and cannot be inherited. This means that although you may place a
height value on a <div> or <article> element of 400px, all of that <div>
or <article>s children will continue to use the default value of height
(auto) unless their height is explicitly set.
8 The CSS Pocket Guide
The CSS specication for each property lists whether that property can
inherit and whether it will inherit its parents value by default.
Actual values: After all the calculations are done and a browser has
processed the document, there are some occasions where the used
value cannot be rendered, so the browser must approximate the
used value, creating the actual value. This can occur when a fractional
pixel unit results from a calculation (50 percent of 99 pixels) or when
a low-color-depth, monochrome display isnt capable of rendering the
exact color calculated.
Throughout this book the rst type are block elements, the second type
inline elements, and the last inline replaced elements.
There are many states a specication moves through on its way to being
nalized, gathering comments and test implementations along the way:
Working Draft: A Working Draft (WD) is the earliest denition of the
specication. The document itself will often be loaded with notes,
questions, or incomplete references. Working Drafts are useful to see
what is ahead and for browser vendors to create test implementations.
There will be certainly be changes to the document and possibly to
individual property denitions in the future because no consensus on
the content of the document has yet been reached.
Last Call Working Draft: When issues, conicts, and questions in the
Working Draft are resolved, there is a Last Call (LC) comment period
announced to solicit feedback on the draft.
Candidate Recommendation: After that Last Call period, a draft may
move onto a Candidate Recommendation (CR), and the working group
solicits test implementations from vendors to make sure what has
been proposed is workable.
Proposed Recommendation: To be a Proposed Recommendation (PR),
the specication is stable, and vendors have created interoperable
implementations.
Recommendation: The bill has become a lawor a nalized
Recommendation (R) as it were.
Chapter 1: CSS Basics 11
Here is where the various specications are along that line and that you
can start using today:
CSS2: CSS2 became a Recommendation in 1998. As a specication, it
has been superseded by CSS2.1, though the term CSS2 may be used
to refer to either.
CSS2.1: As this book is being written in the later part of 2010, the CSS2.1
specication is being readied for PR status. CSS2.1 made changes to
CSS2 by updating technical descriptions and removing properties to
better reect implementation (or total lack of implementation) of the
previous Recommendation.
CSS3: With CSS3, the specication has been split into modules as a way
to control the complexity of any given piece of the large undertak-
ing as well as provide user agents a clear means to carve out which
areas they may not support due to technical device limitations. Some
modules are CRs with better support and implementations, and others
have yet to be written.
For the updated status of CSS2.1 and the various CSS3 modules, see
http://www.w3.org/Style/CSS/current-work. And with all these specica-
tions, CSS3 modules in particular, refer not just to the specication status
but also to browser compatibility charts for implementation details on
the various properties you may want to use.
12 The CSS Pocket Guide
It is important, however, that you do pick and write to both the DOCTYPE
and codication of the standards and the semantic rules of the specica-
tion. Though there are rules for handling markup errors in some speci-
cations, invalid markup such as improperly nested elements or tags that
are never closed can often lead to unexpected styling consequences. In
a similar vein, poor markup semantics may muddy up your selectors and
make your CSS code difcult to follow.
The term for the broad category of anything that can consume a web
document is a user agent. User agents include the typical web browser
but also tools such as screen-reading applications, feed readers, Google
and other search engine spiders, and other programmatic interfaces.
Devices are the hardware the user agents run on and often dictate what
features that user agent can support. A smartphone may have a smaller
screen than a desktop computer, a printer takes on the characteristics of
a printed page, and a Wii may display content on a standard-denition
television screen.
media, while printers, which output onto multiple xed-sized parts, are
considered paged media.
<head>
<link rel=stylesheet type=text/css src=global.css>
</head>
The type attribute denes which language is used in the style sheet. It
is required for HTML4 and XHTML, but it is optional in HTML5 (defaulting
14 The CSS Pocket Guide
to text/css). The src attribute denes the location of the CSS document;
if it is a relative path, it is relative to the location of the referencing HTML
document.
<head>
<style type=text/css>
[...]
</style>
</head>
The type attribute denes which language is used in the style sheet. It is
required for HTML4 and XHTML, but it is optional in HTML5 (defaulting to
text/css).
HTML5 also denes a scope attribute that allows the <style> element
note
to be used inside a block of content, not just the head element.
@import Rule
You can use the @import rule at the top of any block of CSS code or CSS
document to dene another CSS document to be included into the
current document or code block. The @import rule must precede all other
rules in the document (with the exception of the proposed @charset rule
from CSS3).
@import imported.css
Chapter 1: CSS Basics 15
You can also use JavaScript to read the contents of style sheets via the
document.styleSheets object, which is a useful technique for creating
bridge libraries to bring support for unsupported CSS properties or selec-
tors to older browsers (discussed in Chapter 13).
Coding Styles
CSS does not rely on whitespace or indentation to parse the values, but
consistent use of whitespace can make code easier to followas can
thoughtful organization of the rules in a document and good use of CSS
16 The CSS Pocket Guide
comments. There is no one right way to format and organize CSS code, but
this section will provide some place to start as you learn CSS and build
and test your code.
Code Locations
CSS has its greatest value when its shared across multiple documents
or entire sites rather than rewritten or copy and pasted from document
to document. As a result, it is common to break style rules into groups of
how they apply to your content:
Global styles: This includes style information that can be applied to the
entire site. These styles should be in one of the rst linked external CSS
documents.
Section or page type styles: This includes style information that can be
applied to a subsection or alternate page type augmenting or chang-
ing the global styles. These styles can be in a separate external style
sheet linked after the global CSS document only from that type of
page, or included in the global CSS document with some class or id
used on an HTML element such as <body> to distinguish the page type.
Page or content-specic styles: This includes style information that is
shared among pages infrequently or not at all. If it is a small amount
of code, it can be placed in either the global or section CSS documents;
however, if more extensive, a third linked document may be used.
Unique documents: It may be that a page type on a site is truly unique
or that a document is intended to not be part of a site or set of other
documents. This is the case with the code used to generate the gures
throughout this book. In these cases, a style block can cut down the
number of external les that need managing or requests being made
to the server.
Chapter 1: CSS Basics 17
<head>
[...]
<link type=text/css href=styles/global.css>
<link type=text/css href=styles/forums.css>
<link type=text/css href=styles/forum_help.css>
[...]
</head>
/**
* Global Styles
* yournewwebsite.com
*
* Contents:
* 1. Basic HTML elements
* 2. Layout Grid
* 3. Header Content Styles
* 4. Page Content Styles
* 4a. Index Page Content (continues on next page)
18 The CSS Pocket Guide
To comment on a CSS rule, place a comment on the line before the rule.
article {
min-width: 500px; /* wide enough for image content */
}
Arrangement of Selectors
Comments arent the only way to help make large amounts of CSS code
easier to read, scan, and maintain. Coding conventions for formatting the
appearance CSS rules and code organization of those rules are another
key aid.
main camps in the formatting for rules, and both have their pluses and
minuses.
Throughout this book I commonly have written rules with one declara-
tion per line and indented one tab from the left.
#footer { [...] }
#footer form.login { [...] }
#footer form.login input[type=text] { [...] }
#footer form.newsletter { [...] }
#footer form.newsletter p { [...] }
#footer form.newsletter input[type=text] { [...] }
#footer form.newsletter input[type=submit] { [...] }
How you organize your rules is also important. The cascades reliance on
appearance order for selectors and specicity is a good starting point
for seeing how a document might be organizedwith general and
generic rules rst, followed by more specic rules for unique content
types or markup structures. But at some point your selectors will be
targeting more unique types of content and not matching the same
20 The CSS Pocket Guide
/*
* Contents:
* 1. Basic HTML elements
* 2. Layout Grid
* 3. Header Content Styles
* 4. Page Content Styles
* 4a. Index Page Content
* 4b. Article Page Content
* 5. Footer Content Styles
*/
2
Web Browsers
Web browsers and their openness to consume what the world serves
up are why we are able to design such rich sites that are easy to update
and alter. Browsers are the yin to the web servers yang. But as a content
creator, the plethora of browsers can be a drag.
In this chapter, you will see some of the ways web browsers impact your
CSS code, learn how to embrace the different platforms and devices that
may view the pages you build, and see some frequent browser-related
quirks and common ways to deal with them.
22 The CSS Pocket Guide
Browser vendors pick the styling based on a mix of accepted practices and
what will work best on their specic operating system and device. These
base style sheets act as the foundation for displaying all web pages.
Often, as in the case of lists and bullets, you may choose to not write
your own CSS and just go with the defaults. Or, you may want to alter
just one or two of these properties and let the rest be, such as changing
the margin and padding for list items but leaving the bullet style for list
items alone.
If you are the curious type, you can nd all eight les that make up the
default style sheet for Firefox 3 via the internal URL resource://gre/res/.
Internet Explorers base style sheet isnt as accessible, but Jon Neil has
tried to reverse engineer it, placing the results at http://www.iecss.com/.
One look at either, and youre sure to be overwhelmed.
You can simply ignore many of these settings, but some such as margins
or padding make creating consistent presentations difcult. In Chapter 13,
Ill cover using a reset to zero out some of these base style rules to
provide an even starting point to code against.
Chapter 2: Web Browsers 23
User Settings
In addition to a browsers baseline list of styles that it applies to HTML
elements, most browsers allow users to customize a few style properties
to make reading and interacting with web sites easier (Figure 2.1).
Figure 2.1
Preferences dialog
box in Opera 10.54
for OS X.
to load them for all sites they visit or to customize specic sites they
frequent.
Rendering Modes
The teams building web browsers have the unenviable position of need-
ing to support the way things have historically worked in their browsers
while at the same time xing bugs and supporting new work by the
W3C. It may seem like web developers should abandon old and buggy
behavior in favor of progress, but the reality is that hundreds of thou-
sands of web sites may have been built, tested, and published with old
behaviors in mind.
Standards Mode
Under Standards Mode, browser rendering engines behave according to
the letter of the standards. The CSS specications are written to be back-
ward compatible, so pages built to todays standards should not behave
differently under some new specication 10 years from now.
In other words, yet-unwritten standards will not change how color works
or how font-family designations are written even if they add features
such as font embedding or new color keywords. In extreme casessuch
as with the box model updatesa new property is created to designate
new behaviors should be followed, but the default behaviors should
match the old specications.
Chapter 2: Web Browsers 25
Quirks Mode
Quirks Mode is a legacy rendering mode in some browsers that allows
the browser to behave like a previous version of that browser. Quirks
Mode, by denition, works differently in various web browsers and does
not fully follow any CSS specication. It is useful mainly for letting old
sites live on without the need for maintenance and for allowing code
built to work only in a specic browser to continue working.
code, and best viewed in . . . graphics. Only a few developers were writ-
ing valid code, reading specications, and using DOCTYPES like those
designating XHTML. This provided an opportunity to use the DOCTYPE
declaration (or lack thereof) to indicate the type of code being written
and therefore to switch between modes.
A missing or invalid DOCTYPE will put a browser into Quirks Mode, as will
the following:
<!DOCTYPE html>
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01//EN
http://www.w3.org/TR/html4/strict.dtd>
<!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0
Transitional//EN>
X-UA-Compatible
Having just two modes is not enough for some, particularly those build-
ing closed or internal applications using web technologies. Microsoft has
shown concern that changes or xes to the browser will break already
tested and deployed code in ways that DOCTYPE switching alone could
not satisfy. The X-UA-Compatible header, when set via an HTTP header or
<meta> tag, was introduced as a way to lock IE8 and beyond into behav-
ing like a specic older version of the browser. The following example
tells the browser that it should behave like IE8 in Standards Mode:
Chapter 2: Web Browsers 27
The next example tells the browser to emulate IE7 and use the DOCTYPE
derived mode:
Targeting Browsers
In a perfect world, there would be no need to send or hide specic styles
to specic browsers or nd ways to accomplish something without CSS
that there are clearly dened properties for. In the real world, you can get
away with being almost perfect. Under Standards Mode rendering, send-
ing different style rules to different browsers is not the norm, but some
projects will require a small tweak here or there to pull a stray browser
back into line.
Here I show three common ways to approach browser targeting and why
they work. The rst two are useful if you need to make minor changes,
and the last is useful if you are making more regular changes, particu-
larly if you have to develop for older versions of Internet Explorer.
28 The CSS Pocket Guide
Browsers that support the child selector will display a red background on
the page, and those that do will display in blue.
In the following example, most browsers will ignore the unknown prop-
erty _height, but IE will instead ignore the _ character and consider it as
a height, giving you a way to send a different value to IE if needed.
div {
height: 200px;
_height: 300px;
}
Chapter 2: Web Browsers 29
If you want to target IE6 and older, you might use the * html hack, which
to most browsers will not apply to any elements because there is no
element above the root <html> tag, but IE got that wrong until version 7.
div.column {
width: 200px;
}
* html div.column {
width: 198px;
}
<!--[if IE]>
<link type=stylesheet src=/css/all_ie.css>
<![endif]--> (continues on next page)
30 The CSS Pocket Guide
<!--[if lt IE 8]>
<link type=stylesheet src=/css/ie_lessthan_8.css>
<![endif]-->
The downside to adding style rules in this manner is that you create two
or three places where code for the same item resides, making it easy
to forget to maintain each set of rules. A comment in the main CSS le
designating where there is additional code can be a useful way to keep
track of things:
IE and hasLayout
In versions 6 and 7, Internet Explorer has an internal method of distin-
guishing when an element in the page needs some special layout
features such as positioning or sizing. Based on the application of certain
styles, such as height or positioning, Internet Explorer places an element
into a bucket that gets extra layout handling or one that doesnt. This
internal ag is labeled hasLayout. The hasLayout ag was not meant
to be exposed to those of us building web sites, but the internal archi-
tecture that relies on this ag is also the source of a few common CSS
bugs. Figure 2.2 shows the indicator present on a <div> element in the
IE Developer Toolbar.
Chapter 2: Web Browsers 31
Figure 2.2 An element with hasLayout revealed via the Developer Toolbar in IE7.
div.columnA {
height: 1%; /* trigger hasLayout by providing a dimension */
}
div.columnB {
zoom: 1; /* trigger hasLayout by using this nonstandard
property */
}
32 The CSS Pocket Guide
IE8 still has the hasLayout property internally, though its effects on
note
layout behavior are mostly resolved.
Browser Grading
In the previous sections, I outlined a few methods commonly used
to work with web browsers, both old and new, to make sure theyre
handling your CSS properly and to target them when they dont.
But creating all these different versions of code for different browsers,
testing them thoroughly, documenting them, and maintaining them over
time can be time-consuming and frustrating.
Figure 2.3
YUI A-grade
browser matrix.
This specic categorization works for the YUI developers but may not for
you. Therefore, the following is a rough outline of the designations I have
found to work for large commercial projects.
A-Grade Browsers
A-grade browsers represent the target platforms when deciding how to
implement a site and what CSS tools and other technologies you can
comfortably use. Browsers such as Firefox 3, Safari 4, and IE7 nd their
way into this classication based on their capabilities or the size of their
user base.
B-Grade Browsers
B-grade browsers may be older versions of common browsers or current
versions of browsers on uncommon operating systems or devices. These
browsers may, but are not expected to, be able to display some CSS2 or
CSS3 features or JavaScript tricks. However, the pages you build should
still be tested in these browsers to make sure they are fully functional,
they are accessible, your branding message comes across, and they dont
appear to look broken.
34 The CSS Pocket Guide
F-Grade Browsers
For the purposes of development, testing, and ongoing support, it may
be useful to explicitly state which browsers or congurations will not
be supported. Visitors with older browsers such as Netscape 6, Internet
Explorer 5, or older mobile devices are F-grade browsers that will just get
what they get and have to make due.
X-Grade Browsers
X-grade browsers are assumed to fall into the A-grade category but
because of a small share of your user base or similarities to browsers
already listed as A-grade, they arent on your radar or testing matrix.
Older point releases, Linux versions, or alternate UI browsers such
as Camino or Flock that use the same rendering engines as A-grade
browsers t in this category.
A+-Grade Browsers
It is increasingly useful to have an extra category called A+-grade brows-
ers dened to allow for some extra air above and beyond the A-grade
category. New CSS3 features such as rounded corners, animations, or
transitions can be used to enhance the experience for some visitors while
not being central to the sites design.
visual effect. This is a great way to ensure support for rounded corners
via border-radius (Chapter 8) or make sure all of your selectors are
understood.
A Practical Strategy
There are many factors that go into how a web page appears to a
visitorso many that it can be overwhelming if you attempt to
understand and control them all. It is important to remember that
ultimately it is your visitor and not you who is in control of their
browsing experience. The only way to stay on budget, to stay on
time, and to stay sane is to gure out what is important to make
your site shine, then pick a method or methods to get you close to
your goal in the most possible scenarios, and nally get comfortable
with letting the rest go.
This page intentionally left blank
3
Selectors
You use selectors to dene the elements on a page that you want to
apply certain properties to. Elements in the document can be matched
based on the HTML tag used, based on class or ID attributes, based
on the relationship to other elements, or based on the current status
in the document. You can also combine simple selectors to form a chain
of conditions that must be met before the style rule is applied.
38 The CSS Pocket Guide
E (Type Selectors)
The type selector selects an element by its type.
* (Universal Selector)
The universal selector matches any element type in the document. It is
implied if there is a sequence of other simple selectors and no specic
type selector is present.
Attribute Selectors
In addition to id and class attributes, any attribute can be used for
selection with via attribute selectors.
[att]
Selects elements with the attribute att, regardless of the attributes
value.
[att=val]
Selects elements with the attribute att with the value equal to val.
[att~=val]
Selects elements with the attribute att whose value includes the word
val in its space-delimited list of words. (Think multiple class names.)
[att|=val]
Selects elements with the attribute att whose value equals val or begins
with val followed by the separator -. This is intended to be used to
match the language subcode for the hreflang attribute.
[att^=val]
Selects elements with the attribute att whose value begins with val.
Added in CSS3.
[att$=val]
Selects elements with the attribute att whose value ends with val.
Added in CSS3.
[att*=val]
Selects elements with the attribute att whose value contains the
substring val anywhere within it. Added in CSS3.
Chapter 3: Selectors 41
Pseudo-class Selectors
Pseudo-classes fall into two groups: dynamic pseudo-classes that repre-
sent a specic state the document or element is in (visited links) and
structural pseudo-classes that represent information about an elements
position in the document tree (the rst list item).
The :hover pseudo-class for nonlink (< a >) elements is not supported
note
in IE6 or earlier but is supported on links as of IE4.
42 The CSS Pocket Guide
The CSS3 Basic User Interface specication has dened selectors for
the additional user interface states of :default, :valid, :invalid,
:required, :optional, :in-range, :out-of-range, :read-only, and
:read-write. These selectors allow for the styling of the various states
available with HTML5 form elements.
Chapter 3: Selectors 43
This is different from selection based on lang or hreflang via the attri-
note
bute selector because the language pseudo-class may be inherited
from a parent element or dened as part of the document headers.
The values odd and even are shortcuts to select every odd (or 2n+1) or
even (2n) item.
Figure 3.1
Zebra striping, or
applying back-
ground colors to
alternating table
rows.
These selectors can be extremely useful for the common design pattern
of using borders as a divider between a set of elements but not outside
them (Figure 3.2).
Figure 3.2
Border on the
rst-child list
item is removed.
Chapter 3: Selectors 45
Pseudo-element Selectors
Pseudo-elements are phantom elements that dont appear in the
HTML document but instead represent a part of the document that the
browser overlays on the document structure to represent properties of
the layout. For example, because of differences in font sizes, line lengths,
and devices, you cannot wrap the text that will appear on the rst line of
a paragraph of text in a <span> tag with much accuracy. However, brows-
ers will place a phantom pseudo-element around just that rst line of
text as if you did.
Chapter 3: Selectors 47
CSS1 and CSS2 dened the rst-letter, rst-line, before, and after
note
pseudo-elements with a single colon (:). To better distinguish pseudo-
elements from pseudo-classes, the CSS3 spec has changed this to two colons (::).
For those four original pseudo-elements, browsers should support both syntaxes.
Other pseudo-elements can be written only with the double colon (::).
Given this example, the F in the word First will be selected by both rules
and be bold and blue, while the S in Second will just be blue.
A drop cap effect can be easily achieved by applying a left oat and an
t ip
increased font size to the rst letter of a block.
p.note::before {
content: NOTE: ;
font-weight: bold;
}
::selection (Selection)
The selection pseudo-element represents a virtual inline element that
wraps any text selected by a visitor. With any selection, you can set a
limited number of properties including the color and background color
of the text.
E F (Descendant Combinator)
Represented by whitespace, the descendant selector describes an
element (F) that is contained within another element (E). The number
Chapter 3: Selectors 49
body * {}
Here, list items that are direct children of an unordered list tag will be
in a sans-serif font, and those that are direct children of an ordered list
will be xed-width.
h1 + p { font-size: 1.2em }
This example will select all paragraphs that come directly after an <h1>
tag and apply an increased font size.
nav ul li:first-child {}
.vevent h2+* {}
ul ul ul ul>li {}
#page .hentry a.entry-title:link {}
div#main form#registration fieldset
input[type=text]:invalid {}
If you are ever unsure of what a selector does, the online tool
SelectOracle (http://gallery.theopalgroup.com/selectoracle/) trans-
lates CSS2 and CSS3 selectors into English (or Spanish) for you.
Chapter 3: Selectors 51
Specicity
If the only thing that governed which property gets applied to an
element is the order in which the selectors appear, working with CSS
would be a never-ending battle of copying and pasting and rearranging
code. Rules of specicityhow specic the description of the element
in the selector is writtenare used to help determine which properties
will apply.
In the previous code, all paragraph elements will have a 20-pixel margin
on each side; however, because the selector matching paragraphs
contained in blockquote elements is more specic, those will be the
desired color green, even though the rule is found before the simple
p selector.
Here specicity and source order are ignored, and the text will be black,
not green.
Selector Strategies
There are an innite number of ways you can write selectors, and there
are often dozens of ways a particular element in a document can be
selected. Well-written and easily maintainable CSS often comes down to
choosing selectors that are just verbose enough to offer the specicity
and distinctions you need to style the various elements of a site.
54 The CSS Pocket Guide
Grouping Selectors
Different selectors can be separated by a comma and be assigned the
same properties. This will allow you to cut down on repeated use of the
same properties, keep your layouts more uniform, and make changes and
small tweaks easier.
This statement gives many block-level elements that may appear in the
content areas of your document the same whitespace.
Selector Speed
The greater the complexity of selectors, in the form of chaining multiple
nodes or using sibling combinators or attribute selectors, the harder
the rendering engine needs to work when parsing the document and
drawing the page. Speed that is measured in milliseconds may not seem
like a factor in the performance of a web site, but tallied over a large
Chapter 3: Selectors 55
Selector Readability
Sometimes selectors or groups of selectors are chosen for their read-
ability and ease of scanning and visually chunking code in the style sheet
document. More verbose selectors can easily be read and matched to
elements in the HTML document structure. The following example takes
that to an extreme:
Although it is clear how these selectors match to a given HTML DOM, the
selectors can be both slow and overly specic.
Selector Reusability
Keeping the pluses and minus of the other strategies in mind, it is often
useful to write complex selectors with an eye toward common markup
patterns and future reuse.
56 The CSS Pocket Guide
Start with good defaults for your simple type selectors to form a baseline
that will make elements behave consistently regardless of where they
appear.
#quickSearch label {}
#quickSearch input[type=text] {}
#quickSearch input[type=submit] {}
aside #quickSearch label {} /* adjust the properties for a
special case */
4
Measurements, URLs,
and Color Units
In the discussion of CSS syntax in Chapter 1, you saw that the second
part of each CSS declaration is a value. In this chapter, youll explore
some common units for dening sizes (<length> and <percentage>),
colors (<color>), and URLs (<url>) for dening these values.
58 The CSS Pocket Guide
Measurements
Dimensions and other measurements, such as font-size, are not just
raw numbers but a number of some specied of units of measure. CSS
has quite a variety of measurement units; the most commonly used are
outlined in the following sections.
Pixels (px)
img.thumbnail { width: 150px; }
div { border-width: 3px; }
Pixel units are not always a pixel or dot but are dened as
note
a relative length measurement based on the given display. High-
resolution media such as print will output 1px as multiple physical dots, and
high-resolution devices such as the 326-dpi iPhone 4 will render a px unit at
an appropriate size.
Ems (em)
h1 { font-size: 1.6em; } /* make h1 font larger than base */
blockquote { width: 20em; } /* keep block readable */
One em unit (<length>) is a relative unit that equates to the font size of
the element. When applied to the font-size property of an element, an
em unit is relative to the parent elements font size. This behavior makes
it useful for keeping the font size for emphasis, headers, and other tags
relative to the base font sizing. Its also useful when applied to dimen-
sions as a way to control readability and line lengths.
Chapter 4: Measurements, URLs, and Color Units 59
Points (pt)
body { font-size: 12pt; }
Percentages ( % )
.column1 { width: 30%; } /* 30% of the containing block
width */
p { line-height: 140%; } /* 140% of the font-size of the
element */
p.note { font-size: 90%; } /* 90% of the parents
font-size */
Correct?
You can nd more about layouts and the box model in Chapter 5.
Pixels and ems are relative lengthbased units: They are relative to some
other measurement. Like em, the ex unit is relative to the size of the font
(the ex-height or height of the character x). CSS3 has dened some
other interesting relative length units such as the following: rem (relative
to the font size of the root element) and vw and vh (relative to the view-
port width and height, respectively). These units are just starting to be
supported in previews of the next generation of browsers but are some-
thing to look forward to using.
Chapter 4: Measurements, URLs, and Color Units 61
URLs
The URL function (<url>) is used to designate the address of a resource
for use in a property such as background-image or list-style-image.
The path of the resource follows the same rules as other uniform
resource identier (URI) usages like link href values in HTML. When using
external style sheet documents, relative paths relate to the document
the CSS rule is found in (the external CSS document) and not the source
HTML document.
URIs can be quoted with single or double quotes or can be left unquoted.
For historical reasons dating back to IE for the Mac, single quotes are
sometimes avoided as a best practice.
data: URIs
The data: URI scheme uses encoded strings to represent le data
inline rather than as a path to an external le. This can be quite use-
ful for small resources such as iconography, list bullets, or font faces
because it cuts down the number of requests to the server or for
mobile applications.
data:[<mediatype>][;base64],<data>
You can nd support for this URI scheme in CSS in Internet Explorer
8+, Firefox, Safari, and Opera. The source code for data: URIs can be
easily generated with The data: URI kitchen tool by Ian Hickson
(http://software.hixie.ch/utilities/cgi/data/data).
62 The CSS Pocket Guide
Basic Colors
The following color units (<color>) dene several different ways to
designate solid colors and can be used for properties like text color,
background-color, and border-color.
#rrggbb or #rgb
In hexadecimal notation, colors are represented by three sets of hexadec-
imal values (base-16), with the rst set representing the red (r) value, the
second representing the green (g) value, and the next representing the
blue (b) value based on how displays add light to create the colors you
see. A value of #000000 represents no light (black), #ffffff represents
the most light (white), and #ff0000 represents only red light (bright red).
#rgb is a shorthand for #rrggbb, which is available to use when the two
r characters match, the two g characters match, and the two b characters
match (#a3b is equivalent to #aa33bb).
rgb(r,g,b)
You can also dene RGB colors using decimal notation (sometimes called
functional notation) along the same 256-step range (0 to 255) that the
hexadecimal values represented. Each value can also be dened as a
percentage of that 256-step range.
You cannot mix integers and percentages in the same color unit desig-
note
nation. White is rgb(255,255,255) or rgb(100%,100%,100%), but not
rgb(255,100%,255).
hsl(h,s,l)
The hue-saturation-lightness color scheme offers a way to look at the
color wheel that can be more intuitive when working with colors of a
similar hue or tonality. Hue (h) is a number from 0 to 360 representing
a radial position on the color wheel (0 or 360=red, 120=green, 240=blue).
Saturation (s) is a percentage value from 0 to 100 percent with values
closer to 0 percent approaching desaturated, or gray. Lightness ( l ) is
again a percentage value from 0 to 100 percent, where 0 percent is black
and 100 percent is white.
Color Keywords
The HTML 4 specication dened the following 16 color keywords and
their corresponding hex values: aqua, black, blue, fuchsia, gray, green,
lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow.
Keywords are case insensitive and are not placed between quotes.
p { color: #fff; }
p { color: #ffffff; }
p { color: rgb(255,255,255); }
p { color: rgb(100%,100%,100%); }
p { color: hsl(0,0%,100%); }
p { color: white; }
The notation you choose to work with can depend on many factors.
Your familiarity with the different color systems, which is the easiest
to transpose from your favorite graphics application uses, or how the
color palette for the site is designed all should impact this decision.
With hsl( ), it can be easier to write transitions via JavaScript, but
watch for browser support issues since its also the newest method of
dening color.
The transparency in the color applies only to the parts of the element
that color applies to and does not affect the transparency of elements it
may contain or other objects like images. I discuss the opacity property,
which applies to the visibility of an entire element, in Chapter 6.
Chapter 4: Measurements, URLs, and Color Units 65
Figure 4.1
Using a transpar-
ent background
color to make
solid text more
readable against
a background
image.
rgba(r,g,b,a)
The r, g, and b values work on the same scale as their rgb( ) unit coun-
terparts discussed earlier in this chapter. The alpha (a) value is a decimal
number from 0 to 1, with 0 being completely transparent and 1 being
fully opaque.
Color units with alpha values of 1 are equivalent to using the solid
t ip
color unit. Consider using that solid color unit instead because it may
be supported by more browsers.
hsla(h,s,l,a)
Like rgba(), hsla() is the same color as hsl() with an added designation
for alpha transparency. This unit is also a decimal number from 0 to 1.
transparent
The transparent color keyword represents a color value that is fully
transparent (and thus red channel or hue designations dont matter).
You can think of it as a shorthand form for (and gets computed in
browsers as) rgba(0,0,0,0).
div {
background-color: rgb(0,0,255);
background-color: rgba(0,0,255,90%);
}
Design
Color theory is far outside the scope of this book and is something you
could study for years; however, here are a few tips for choosing the color
scheme for a web site:
Design applications such as Adobe Photoshop offer a detailed color
picker that can be switched between RGB, HSL, and other color
systems, making for easy translations into CSS units.
Adobe Kuler is a tool for creating, browsing, and bookmarking color
swatches from your browser or your desktop. You can make swatches
based on a color wheel or drawn from an uploaded image le
(http://kuler.adobe.com/).
Maintenance
Maintaining consistent color usage across a large amount of CSS code
can sometimes be difcult. Color units are dened in so many different
declarations across so many different elements that it is easy to keep the
shade of gray being used the same or know what color should be used
for links. Here are some hits for making the task easier:
Pick one color unit type, and stick with it so searching for a color when
it is time to change it is easier. Dont use #ff0000, rgb(100%,0,0) and
the keyword red interchangeably.
68 The CSS Pocket Guide
Maintain a style guide that lists all the colors used on the site along
with the preferred unit value to represent them, and use only these
colors.
For complex or very large sites, consider using a CSS preprocessor like
those discussed in Chapter 13 that allow you to dene placeholders for
color values and dene a specic color value only once in your code.
5
Top
TM Margin (Transparent)
TB Border
TP Padding
BP
BB
BM
Bottom
Margin edge
Border edge
Padding edge
Content edge
Figure 5.1 The standard box model. The T, R, B, and L abbreviations represent the top,
right, bottom, and left values of each property.
Chapter 5: The Box Model 71
Properties
width
The width property denes the width of an element.
<length>: The width will be a xed dimension.
height
The height property sets the height of an element.
<length>: The height will be a xed dimension.
margin
The margin property sets the four margins surrounding an element. Each
side may take one of the following property values:
<length>: The margins will be a xed dimension.
margin-top: 1px;
margin-right: 20%;
margin-bottom: 0;
margin-left: 40px;
margin: 2em; /* shorthand: all sides */
margin: 2em 0; /* shorthand: top & bottom; right & left */
margin: 2em 0 1em; /* shorthand: top; right & left; bottom */
margin: 2em 0 1em 10px; /* shorthand: top; right; bottom;
left */
When margins from two elements contact each other on a page, they
collapse into one another with the resulting effect that the margin
between each element is the size of the largest of the two margin
properties. For example, if there is an <h2> with a bottom margin of
20 pixels followed by a paragraph with a top margin of 10 pixels, the
space between the two elements will be 20 pixels, not 30.
padding
The padding property sets the four padding dimensions between an
elements content area and its border. Each side may take one of the
following values:
<length>: The length will be a xed dimension.
padding-top: 1px;
padding-right: 20%;
padding-bottom: 0;
padding-left: 40px;
Chapter 5: The Box Model 73
border-width
The border-width property sets the size of an elements border.
<length>: The border width will be a xed dimension.
border-top-width: 2px;
border-right-width: 0;
border-bottom-width: 10px;
border-left-width: 1px;
border-width: 2px 0 10px 1px; /* shorthand: top; right;
bottom; left */
In Chapter 8, I discuss some of the visual options for borders in detail, but
only border-width impacts the dimensions of an element.
74 The CSS Pocket Guide
overflow
The overflow property denes what is done if the content in a box is too
big for its dened space. The possible values for the overflow property
are as follows:
visible: Shows the content outside of the box (default)
hidden: Clips the content and hides what falls outside the dimensions
of the box
scroll: Clips the content and always draws scrollbars to allow for
access to additional content
auto: Clips the content and draws scrollbars only when they are needed
The overow behavior for the width and the height of a box can be indi-
vidually set with the overflow-x and overflow-y properties.
By default, Internet Explorer will not let the content ow out of the
note
box but instead expand the box to t the content as if width or height
were min-width or min-height. This is partly why a short height is used in the
hasLayout xes discussed in Chapter 2.
article {
width: 100%; /* let element fit parent */
min-width: 200px; /* ensure content isnt too narrow */
max-width: 900px /* ensure content isnt too wide */
}
Chapter 5: The Box Model 75
Nesting Elements
When nesting HTML elements, the inner elements box is drawn inside
the content area of the outer element. This results in an assortment of
ways you can combine the properties to achieve the same visual effect or
whitespace. As you nest elements, you compound the buildup of proper-
ties along the elements at the edge of these boxes.
To create the simple illustration shown in Figure 5.2 from the nested
elements <div><div></div></div>, you have a number of possibilities
as to how you split the 100-pixel gray area between the outer element
border area and the inner elements content area. That 100 pixels can be
split however youd like between the adjacent padding-margin-border
area. Depending on that choice, it may be possible to create the 50-pixel
inner white area with the inside border padding.
Figure 5.2
Content area
surrounded
by 50 pixels of
white and then
surrounded by
100 pixels of gray.
76 The CSS Pocket Guide
Example 1:
div {
margin: 0;
padding: 50px;
border: 1px solid #999;
background: #ccc;
}
div div {
margin: 50px;
padding: 50px;
border: none;
background: #fff;
}
Example 2:
div {
margin: 0;
padding: 100px;
border: 1px solid #999;
background: #ccc;
}
div div {
margin: 0;
padding: 0;
border: 50px solid #fff;
background: #fff;
}
Chapter 5: The Box Model 77
Example 3:
div {
margin: 0;
padding: 75px;
border: 1px solid #999;
background: #ccc;
}
div div {
margin: 25px;
padding: 40px;
border: 10px solid #fff;
background: #fff;
}
Gutters surrounding text and other content are often best created by
setting padding on the outer element. This will ensure the gutters are
set to a consistent size regardless of the content within the container.
It is more exible and more easily maintained than the alternative of
setting the left and right margin or padding on any possible child of
that container.
In the next section, youll see how using the box properties of a unique
child element might be more practical.
78 The CSS Pocket Guide
The rst example (Figure 5.3) overlaps two sibling elements by using a
negative top margin.
Figure 5.3
Negative top
margin causing
elements to
overlay.
header {
background: #999;
padding-bottom: 2em;
}
article {
border: 1px solid #999;
background: #fff;
margin: 1em 2em;
}
header+article {
margin-top: -1em;
}
[...]
<header>
Chapter 5: The Box Model 79
<h1>Header Content</h1>
<p>More Header Content</p>
</header>
<article>
<p>Some article content which will break into the header
above</p>
</article>
<article>
<p>Some content of another article which will follow as
normal</p>
</article>
In the second example (Figure 5.4), negative margins are used to bleed
into the gutter provided by a 50-pixel padding on the containing
element.
Figure 5.4
Negative
margins causing
element to
enter its parents
padding area.
div {
width: 400px;
padding: 0 50px;
} (continues on next page)
80 The CSS Pocket Guide
div h1 {
margin-left: -50px;
background: #999;
}
div h2 {
margin: 0 -50px;
background: #CCC;
}
[...]
<div>
<h1>Header 1 will break the left gutter</h1>
<h2>Header 2 will break both gutters</h2>
<p>Paragraph will respect both gutters</p>
</div>
<div>
<p style="margin: 0 0 0 0;">margin: 0 0 0 0;</p>
</div>
<div>
<p style="margin: 0 auto 0 0;">margin: 0 auto 0 0;</p>
</div>
<div>
<p style="margin: 0 auto 0 auto;">margin: 0 auto 0 auto;
</p>
</div>
Chapter 5: The Box Model 81
<div>
<p style="margin: 0 0 0 auto;">margin: 0 0 0 auto;</p>
</div>
Take a container <div> that is 500 pixels wide, as shown in Figure 5.5. If
a 300-pixel wide <p> is inside that container, then you have 200 pixels of
room to spare. If both margins on the <p> are 0, then the paragraph will
be ush left. However, the denition of an auto margin value is that it
will ll the container. A right margin of auto and left of 0 will not particu-
larly change anything in the layout (the empty space is still on the right),
but having both right and left margins set to auto will cause the space to
be split between the two margins, and the <p> will appear centered just
as if you had done the calculations yourself and set the margins to 100
pixels each.
Figure 5.5
Auto margin
examples.
box-sizing
The box model used when calculating and placing borders and padding
areas can be set using the box-sizing property.
content-box: The width and height dimensions refer to the content
area with padding and borders drawn outside (default).
82 The CSS Pocket Guide
border-box: The width and height dimensions contain the border and
padding as well as the content of the element, while an elements
margins continue to fall outside of this area.
Chapter 5 covered how block-level elements are given their shape and
size. Before jumping headrst into creating multicolumn layouts with
these blocks, you need to learn how to position elements in your docu-
ments in relationship to the other items on a page.
84 The CSS Pocket Guide
You have three ways to change the default positioning and interaction
between elements in the top-down blob of content: You can force an
element to behave like a different type of element, you can pull the item
out of the ow completely, or you can pull the item to the side of its
container and allow other items to wrap around it.
display
The display property is the key to the entire layout castle. Ive already
covered block elements and inline elements, but you need a number of
other element types to dene all the content that might display on a
web page, including the following:
inline: Creates one or more inline boxes, the familiar inline content
Position
The positioning of an element is based on the length of the box offset
parameters: top, right, bottom, and left. Typically, top and left will be
used for positioning elements since the top-left corner of the item being
measured fromthe beginning of a boxis easily understood in normal
document ows.
static
static is the default value where an element is rendered in the normal
ow and not uniquely positioned. The positioning parameters top, right,
bottom, and left do not apply.
relative
In relative positioning, an elements position is calculated as normal, and
then the offset positioning is applied relative to this normal position.
Relative positioning does not take the element out of the normal ow,
which leaves a space behind in the elements original position.
A relative positioned element with box offsets set to 0 (or undened) will
appear in its normal position; however, it will create a new point of origin
for any of its child elements that may be positioned absolutely.
86 The CSS Pocket Guide
absolute
Absolute positioning takes the element out of the normal document
owcollapsing any space it may have otherwise usedand positions
it in relation to the origin point created by the last-positioned containing
block.
The code used for Figure 6.1 demonstrates how to use absolute position-
ing to place elements at the four corners of its containing element.
Figure 6.1
Elements placed
into four corners
with absolute
positioning.
div {
position: relative;
width: 150px;
border: 1px dotted #999;
}
div div {
position: absolute;
width: 25px;
height: 25px;
background-color: #ccc;
border: none;
text-align: center;
}
Chapter 6: Positioning and Floats 87
div .corner1 {
top: 0;
left: 0;
}
div .corner2 {
top: 0;
right: 0;
}
div .corner3 {
bottom: 0;
right: 0;
background-color: #999;
}
div .corner4 {
bottom: 0;
left: 0;
background-color: #999;
}
<div>
Here is some content before the four child div elements.
<div class="corner1">1</div>
<div class="corner2">2</div>
<div class="corner3">3</div>
<div class="corner4">4</div>
Here is some content after the four child div elements.
</div>
When content is pulled out of the normal document ow, the height of
the parent element shrinks. It is easy to run into cases where the parent
shrinks too much and the positioned element overows its parent
container. You can force the space open with height, width, or padding
88 The CSS Pocket Guide
on the parent element, as I have done in Figure 6.1. The document, being
the root container, will similarly shrink, and you could potentially over-
ow your document and its scrollable area.
Figure 6.2
A container
element
shrinking to t
only the content
in the normal
document ow.
fixed
Fixed positioning is based on the viewport and not the document. The
origin for xed-positioned elements is the root node (<html>). The top-
left position of 0, 0 would be the top-left corner of the viewport, and
similarly the bottom-right position of 0, 0 is the bottom-right corner.
elements such as toolbars or banners and not for laying out an overall
web page.
The root element of the document is the initial containing block for
which absolute positioning is measured from. However, if any other
element is positionedrelatively, absolutely, or xed in the viewport
it becomes the new origin for its descendant elements. This behavior is
probably best illustrated with an example (Figure 6.3).
div {
border: 1px dotted #000;
padding: 20px;
}
#containingBlock {
position: relative;
}
#innerPositionedBox {
position: absolute;
top: 0;
left: 0;
background-color: #000;
}
[...]
<div id="containingBlock">
<div>
<div>
<div id="innerPositionedBox">
</div>
</div>
</div>
</div>
<div>
<div id="containingBlock">
<div>
<div id="innerPositionedBox">
</div>
</div>
</div>
</div>
Since you cannot escape this behavior and position an element with
respect to the root element once it has a different containing block
dened, it is important not to overuse positioning properties, thus need-
lessly creating new containing blocks. Sometimes this is inescapable, and
in those cases math can be your friend (either with paper and pencil or
in code via JavaScript)you can calculate the position of the containing
block (and any of its containing blocks) and work your way back up to the
root element.
92 The CSS Pocket Guide
z-index
The z-index property applies to any positioned box and can be used to
control the layering of boxes from back to front. The higher the integer
value, the closer to the viewer the element appears.
visibility
The visibility property determines whether an element renders and
can be seen. Unlike setting the display property to none, an element
with a visibility of hidden still affects layout and will take up space.
Unlike the opacity property, individual descendants of a hidden element
can be shown by setting their visibility to visible.
visible: The element is rendered.
float
An element with a float value of left or right is taken out of the
normal ow of a document and shifted to one side of the containing box.
The content that follows it in the document wraps around the oated
elements new position.
none: An element is not oated and behaves as normal.
Think of a small photo that is moved to the right and has text owing
around it; you now have the basic idea of how an element (the photo)
behaves when oated (Figure 6.5 on the next page).
94 The CSS Pocket Guide
Figure 6.5
Two small
elements oated
inside text
content.
Figure 6.6
Text wrapped
around a oated
element.
img {
float: left;
}
p {
border: 5px solid #666;
Chapter 6: Positioning and Floats 95
padding: 15px;
background: #ccc;
}
[...]
<img src="images/1.png" width="67" height="67" alt="1" />
<p>Here is some text after a left floated image for
illustration purposes. Lorem ipsum dolor sit amet,
consectetur adipisicing elit.</p>
Figure 6.7
A margin placed
on the oated
element to create
space between
it and the
content wrapped
around it.
img {
float: left;
margin: 20px;
}
If multiple elements are oated and would appear along the same edge,
then they are arranged horizontally with the earliest element in the
96 The CSS Pocket Guide
Figure 6.8
Left-oated
blocks of various
sizes.
Figure 6.9
Right-oated
blocks of various
sizes.
Chapter 6: Positioning and Floats 97
With modern layout techniques, oated elements are used for much
more than small bits of content in elements and text wrapping. They
can be the basis for placing elements on opposite sides of the same
line, controlling a series of tabs, and even controlling multiple-column
layout grids.
clear
Floating is often used instead of positioning or large margins because
the content-wrapping effects are desired, but the wrapping of a tall
oated element can often extend into later content in an undesirable
way. The clear property is used to insert a break when encountering a
new section of the layout or another unique record in a list or some other
reason for wanting to stop the wrapping effect.
none: The element does not clear any oats.
left: The element will be shifted down to sufciently clear the bottom
edge of any previous left-oated elements.
right: The element will be shifted down to sufciently clear the
bottom edge of any previous right-oated elements.
both: The element will be shifted down to clear and begin after all
oated elements.
98 The CSS Pocket Guide
In Figure 6.10 you can see what happens when the oated element
from one list item bleeds into the following one; things really start to
go haywire.
Figure 6.10
The effect of
oated elements
extending past its
parent element
into the following
content.
li {
border: 1px solid #000;
}
img {
float: left;
margin-right: 0.5em;
}
[...]
<ul>
<li>
<img src="images/1.png" width="67" height="67"
alt="1" />
<p>Here is some text associated with the first list
item</p>
</li>
<li>
<img src="images/2.png" width="67" height="67"
alt="2" />
<p>Here is some text associated with the second list
item</p>
</li>
Chapter 6: Positioning and Floats 99
<li>
<img src="images/3.png" width="67" height="67"
alt="3" />
<p>Here is some text associated with the third list
item</p>
</li>
</ul>
You can set the clear property to left or both on the <li> element, as
shown in Figure 6.11, to make sure that for each new item nothing from
the previous item interferes.
Figure 6.11
clear:left
used to stop the
previous oats
before each new
item.
li {
border: 1px solid #000;
clear: left;
}
The CSS 2.1 Specication has some quite detailed and sometimes
t ip
difcult-to-understand text explanations of the interaction
of oated elements, margins, padding, and clear. It also has a number of
easy-to-understand and useful illustrations (http://www.w3.org/TR/2009/
CR-CSS2-20090908/visuren.html#oats).
This page intentionally left blank
7
Page Layouts
Page layout with HTML and CSS begins with establishing a layout grid
or set of columns to ow content into, but what you do with individual
content types or items once you get them into a column is just as
important.
Luckily, the techniques used for both page layouts and content layouts
are the same. Whether youre working with elements of the content that
fall inside each column, content in the page header or footer, or reusable
widgets, content elements must be laid out in their own grid using the
same techniques that make up the larger page layout.
Content Is King
As powerful as CSS is, its only purpose is to describe presentation
for the underlying HTML content. Strong, semantically appropriate
markup is the foundation that allows CSS to work its magic.
Source order, or the order in which content is read when not styled, is
also an important consideration when considering which techniques
to use to style content. Some techniques may be easier to use to visu-
ally pull content from the middle of the document tree or from the
beginning or end of a section.
Figure 7.1
Establishing new
containing blocks
for individual
content items
and positioning
the prole icon.
.badge {
position: relative;
width: 155px;
padding: 5px 5px 5px 72px; /* create gutter */
font-size: 12px;
background: #eee;
}
.badge .photo {
position: absolute;
top: 5px; /* match padding on .badge */
left: 5px; /* match padding on .badge */
border: 1px solid rgb(94,94,94);
}
.badge ul {
padding-left: 0;
list-style: none;
}
[...]
<div class="badge vcard">
<a href="/users/JohnDough" class="fn">John Dough</a>
<img class="photo" src="images/profile_icon.png">
<ul class="meta">
<li>Status: Offline</li> (continues on next page)
104 The CSS Pocket Guide
<li>Registered: 8/22/2010</li>
<li>Total Posts: 823742</li>
<li>Website: <a href="http://example.com/" class="url">
example.com</a></li>
</ul>
</div>
Figure 7.2
A small
content block is
positioning in the
gutter of a larger
element using
oats.
.container {
padding: 5px;
border: 1px solid black;
}
Chapter 7: Page Layouts 105
.main {
height: 200px;
margin-left: 110px;
border: 1px solid black;
}
.floated {
float: left;
height: 150px;
width: 98px;
border: 1px solid black;
}
[...]
<div class="container">
<div class="floated">
.floated
</div>
<div class="main">
.main
</div>
</div>
Faux Columns
In the previous oat example, youll notice that the height of the left
element is shorter than the right. If you were to place a background color
or image on this element, it wouldnt extend past this element to cover
the entire left gutter or column. A background image on the containing
element will continue through the whole space, so use that opportunity
to apply a background image to provide the appearance of full-height
columns. The left column in Figure 7.3 is an example of this faux column
technique.
Figure 7.3
Background
image on the
container ele-
ment providing
the appearance
of a column that
extends past the
content.
.container {
padding: 5px;
border: 1px solid black;
background: url(images/bg_faux_columns.png) repeat-y left
top;
}
.main {
height: 200px;
margin-left: 110px;
border: 1px solid black;
}
.floated {
float: left;
height: 150px;
Chapter 7: Page Layouts 107
width: 98px;
border: 1px solid black;
}
[...]
<div class="container">
<div class="floated">
.floated
</div>
<div class="main">
.main
</div>
</div>
Figure 7.4
A composite of
four separate
background
images working
in coordination.
html { /* #1 */
margin: 0; padding: 0;
background: #fff url(images/fourbg_html.png) repeat;
}
body { /* #2 */
margin: 0; padding: 0;
background: url(images/fourbg_body.png) repeat-x left top;
}
.container { /* #3 */
width: 400px;
height: 500px;
margin: 0 auto;
padding: 0;
background: url(images/fourbg_container.png) repeat-y left
top;
}
.masthead { /* #4 */
height: 100px;
background: url(images/fourbg_masthead.png) no-repeat left
top;
}
[...]
Chapter 7: Page Layouts 109
<html>
<body>
<div class="container">
<div class="masthead">
</div>
</div>
</body>
</html>
Figure 7.5 A set of navigation-based list items oated into a horizontal format.
ul.nav {
height: 16px;
}
ul.nav li {
float: left;
height: 16px;
padding: 0 0.5em;
font-size: 12px; (continues on next page)
110 The CSS Pocket Guide
list-style: none;
border-left: 2px solid black;
}
ul.nav li:first-child {
border-left: 0; /* remove border from outside item */
}
[...]
<ul class="nav">
<li><a href="#">First Page</a></li>
<li><a href="#">Second Page</a></li>
[...]
</ul>
Figure 7.6
Negatively
positioned
element breaking
its container.
Chapter 7: Page Layouts 111
article {
position: relative;
[...]
margin-left: 50px;
border: 1px solid black;
}
article time {
position: absolute;
top: 10px;
left: -50px;
[...]
background: url(images/flag.png) no-repeat right top;
}
[...]
<article>
<time>13th</time>
</article>
#menu li ul {
position: absolute;
display: none;
left: 0;
}
[...]
#menu li:hover ul {
display: block;
}
A Two-Column Layout
If you were to make the .main and .floated blocks earlier in the chapter
(Figure 7.3) wide enough, then you have a two-column layout. That isnt
all there is to do, however, because that example has two important
points of failure:
If the sidebar column is taller than the main content area, it will
escape the bottom bounds of the container and force the wrapping
of the following content such as the footer.
The code provided requires the oated element to appear before
the main content area in the source HTML document, which may
be undesirable.
Both problems can be solved with minor changes, as the following exam-
ple demonstrates (Figure 7.7).
Figure 7.7
The results of
changes to the
earlier two-
column layout.
114 The CSS Pocket Guide
.container {
width: 534px;
padding: 5px;
border: 1px solid black;
background: url(images/bg_faux_columns.png) repeat-y left
top;
overflow: auto;
}
.main {
float: right;
height: 200px;
width: 420px;
margin-left: 0;
border: 1px solid black;
}
.sidebar { /* renamed for clarity */
float: left;
height: 220px;
width: 98px;
border: 1px solid black;
}
[...]
<div class="container">
<div class="main">
.main
</div>
<div class="sidebar">
.sidebar
</div>
</div>
Chapter 7: Page Layouts 115
.container {
width: 534px;
padding: 5px;
border: 1px solid black;
background: url(images/bg_faux_columns.png) repeat-y right
top;
overflow: auto;
}
.main {
float: left;
height: 200px;
width: 420px;
margin-left: 0;
border: 1px solid black;
}
.sidebar {
float: right;
height: 220px;
width: 98px;
border: 1px solid black;
}
Chapter 7: Page Layouts 117
A Three-Column Layout
You can easily extend the previous two-column layout to incorporate
a margin wide enough to oat two of the three columns into. However,
the size of the main column or the source order may dictate that a differ-
ent arrangement is needed. Here is some trickery with oating and
negative margins to get small left and right columns and allow the main
content area to be rst in the document (Figure 7.8).
Figure 7.8
A three-column,
xed-width
layout.
.container {
width: 534px;
padding: 5px;
border: 1px solid black;
background: none;
overflow: auto;
}
.main {
float: left;
height: 200px;
width: 318px; /* narrower to fit new element and gutter */
margin-left: 107px; /* make room for left column */
border: 1px solid black;
}
.left_sidebar { /* renamed, again, for clarity */
float: left; (continues on next page)
118 The CSS Pocket Guide
height: 120px;
width: 98px;
margin-left: -426px; /* shift _past_ .main */
border: 1px solid black;
}
.right_sidebar {
float: right;
height: 180px;
width: 98px;
border: 1px solid black;
}
[...]
<div class="container">
<div class="main">
.main
</div>
<div class="left_sidebar">
.left_sidebar
</div>
<div class="right_sidebar">
.right_sidebar
</div>
</div>
Figure 7.9
A mixed column
layout with two
exible content
columns and
one xed-width
sidebar.
.container {
width: auto;
padding: 5px 107px 5px 5px; /* room for right sidebar */
border: 1px solid black; (continues on next page)
120 The CSS Pocket Guide
background: none;
overflow: auto;
}
.main_left {
float: left;
height: 200px;
width: 48%;
margin-right: 5px;
border: 1px solid black;
}
.main_center {
float: left;
height: 120px;
width: 48%;
border: 1px solid black;
}
.right_sidebar {
float: right;
height: 180px;
width: 100px;
border: 1px solid black;
margin-right: -102px;
}
[...]
<div class="container">
<div class="main_left">
.main_left
</div>
<div class="main_center">
.main_center
</div>
Chapter 7: Page Layouts 121
<div class="right_sidebar">
.right_sidebar
</div>
</div>
You may be looking at that previous example and thinking that the math
doesnt add up, and youd be rightit doesnt. When mixing percentage
measurements, you have to fudge the numbers just a little. A 50 percent
width plus another 50 percent width plus 4 pixels worth of borders plus
a 5-pixel margin is clearly greater than the 100 percent width that the
container has to spare. It is a better bet that 96 percent of that space
will leave 9 pixels to spare, which, in this case, will be true so long as the
containers content width is at least 225 pixels ( 9 pixels / (100 percent
96 percent) * 100). If the content width is larger than 225 pixels, that
4 percent width will be larger than 9 pixels, but in many situations, those
few extra pixels are a fair trade-off for having a mixed layout.
You can use the min-width and max-width properties to cap the size of
otherwise liquid columns or column wrappers. In the following code, the
container used in the previous examples is allowed to grow to between
600 pixels and 1000 pixels and then is centered on the page if it goes
beyond the maximum width.
122 The CSS Pocket Guide
.container {
width: auto;
min-width: 600px;
max-width: 1000px;
margin: 0 auto;
}
Chapter 12 covers media queries, which let you match browser or device
dimensions (or other properties) with different CSS code. This can be
yet another method of introducing a exible, adaptive layout with
constraints.
8
Backgrounds and
Borders
Through the color and images of backgrounds and borders, a sites owner
or creator can transform bland pages of text into designs that convey a
mood, aesthetic, and branding. That is asking a lot of just two seemingly
simple properties, but as youll see throughout this chapter, theyre very
exible and powerful properties.
124 The CSS Pocket Guide
Backgrounds
Backgrounds are an integral part of styling an HTML document. Solid
colors, patterns, tiles, gradients, unconventional borders, and nonrect-
angular shapes can all be achieved by applying the various background
properties to the right element.
background-color
The background-color property is applied throughout the content area
of the element and is drawn behind any background-image that is set.
<color>: The color of the background
background-image
The background-image property is used to specify a background image
for an element.
<uri>: The path to the image le in the format url(path) or quoted
with single or double quotes such as url("path") and url('path').
none: No background image is used (default).
background-repeat
The tiling of background images is set with the background-repeat
property. The following keywords are the most commonly used values:
repeat: The image tiles in both directions (default).
background-attachment
The background-attachment property denes how a background posi-
tion is determined.
scroll: The background is xed with respect to the specic element
and scrolls along with it in the document. (This is the default.)
fixed: The background is xed with respect to the viewport and does
not scroll with the element; it appears only when that element is
over its position in the viewport.
background-position
The background-position property species the position of the back-
ground image (or the positioning of the rst background-image tile when
repeating) given as a set of two values: horizontal and then vertical.
126 The CSS Pocket Guide
<length>: A xed length for the offset from the upper-left corner.
The CSS3 specication adds the ability to use pairs of values where the
rst of the pairing describes the edge measured and the second the
offset length or percentage from that edge. At the time of this writing,
however, no major browsers support the offset syntax.
background (Shorthand)
The background shorthand property allows for assigning the indi-
vidual background properties (background-color, background-image,
Chapter 8: Backgrounds and Borders 127
The previous code would set up nonrepeating top and bottom images
with a tiled image the height of the element beneath them.
128 The CSS Pocket Guide
There is very little reason to slice an image for use in CSS. If it appears as
a cohesive graphical element in the source Photoshop document, then it
can most likely remain so in the HTML build if you nd the right element
to which to attach it. A typical HTML document structure has a body,
a wrapper for the header, center columns or footer, various sections or
articles, and then nally the text. Find the element in that hierarchy that
is best suited to which to attach the background image.
Stretching the size of an element with excess padding just to make space
for an image is common practice when working with columns or link
icons. Overlapping elements with negative margins (Chapter 5) can be a
great way to get that background image attached to the header element
to bleed into the content of the page.
entirely and extending the content area of the list item via padding-left,
you can make room to shove a new image into (Figure 8.1):
ul.big {
margin: 0;
padding: 0;
}
ul.big li {
font-size: 28px;
margin: 0 0 0.25em;
padding: 0 0 0 30px; /* image is 23x23, shift left to make
room */
background: url(images/big_bullet.png) no-repeat 0 6px;
}
[...]
<ul class="big">
<li>big item one</li>
<li>another big item</li>
<li>see the big bullet</li>
<li>last item</li>
</ul>
Figure 8.1
Icons placed in
gutter created by
padding.
130 The CSS Pocket Guide
The same method is applied for iconography like PDF icons next to links
that match the selector a.pdf or a[href~=.pdf] or warning signs before
any p.note.
Connecting Backgrounds
Elements such as section headers or tabbed boxes may have fancy
borders that open up into the content below like the tab on a folder.
Because the position of the tab on that folder varies, the opening in the
top of the content area needs to change. Here again you can use visual
tricks to make the elements backgrounds overlap. The following sample
(shown in Figure 8.2) uses borders, background colors, and relative posi-
tioning to shift the header into the content that follows and create the
appearance of a nonrectangular border:
h1 {
position: relative;
top: 3px; /* shift down the size of the border */
background: #fff;
margin: 0 0 0 20%;
padding-bottom: 3px; /* retain the space of the missing
border */
border: 3px solid #999;
border-bottom: none;
}
h1+p {
background: #fff;
margin: 0;
padding: 1em;
border: 3px solid #999;
}
[...]
Chapter 8: Backgrounds and Borders 131
<h1>Heading</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. [...]</p>
Smart Tiling
Whenever using background images with elements that can become
quite long on one end or another, such as the height of a content column
or the width and height of the body element, there are two options for
covering the full length of that block: You can pick a design that can tile,
or you can make the image ridiculously big.
The ribbon pictured in the rst part of Figure 8.3 (on the next page)
cannot be tiled horizontally as the background image on the <body>
element without repeating the dip at some point. Make the image 4000
pixels wide and continue the at horizontal lines, and you may be con-
dent no one will see the dip again; however, the le size and overhead
once the image is loaded will be large.
132 The CSS Pocket Guide
Figure 8.3
Repeating
pattern with a
break, separated
into two parts.
Splitting the image into two pieces, one that tiles and one that sits above
and covers up the tiling portion, can solve the problem:
body {
margin: 0;
padding: 0;
background: #fff url(images/tiled_horizontal_bars.png)
repeat-x center top;
}
header {
height: 100px;
width: 400px;
margin: 0 auto; /* center the block */
padding: 0;
background: #fff url(images/the_dip.png) no-repeat center top;
}
When working with the background of the document, you have an added
challenge that you dont want to extend the content areas unnecessar-
ily and create scrollbars on the viewport. Dont forget that in addition to
the <body> element, <html> can also be styled and used as another layer
before you have a need for wrapper elements or other articial hooks.
Chapter 8: Backgrounds and Borders 133
.tabs .tab {
float: left;
width: 177px;
height: 26px;
margin: 0;
padding: 4px 0 0;
list-style: none;
text-align: center;
background: url(images/tabs.png) 0 -31px no-repeat;
}
.tabs .tab.active {
background-position: 0 -62px;
}
.tabs .tab.special {
background-position: 0 -93px;
}
.tabs .tab.disabled {
color: #ccc;
background-position: 0 0;
}
[...]
<ul class="tabs">
<li class="tab">tab one</li>
<li class="tab active">tab two</li>
<li class="tab special">tab three</li>
<li class="tab disabled">tab four</li>
</ul>
Chapter 8: Backgrounds and Borders 135
Placing every image used on a complex site into the same sprite le
t ip
may create a management nightmare. Look to create sprites that
represent similar types of images and balance complexity with request and
performance overhead.
Border
In Chapter 5, border was introduced as the border on a block element
that is drawn between the padding and the margin of an element.
Borders are drawn in front of the elements background, which has an
impact on the display of border styles with gaps (dashed) and with back-
ground positioning.
border-color
The border-color property takes one to four <color> values signify-
ing the colors for the border on each of a blocks four sides. Like with
margin and padding, when one color is provided, it applies to all sides.
With two, the rst value applies to the top and bottom, and the second
applies to the right and left. With three, the rst applies to the rst
top; the second applies to the left and right; and the third applies
to the bottom. With four values, it applies to each side clockwise
from the top. border-color can be expanded to border-top-color,
border-right-color, border-bottom-color, and border-left-color.
border-style
The design of the border is set via one to four keywords assigned to the
border-style property.
inset: Gives the appearance that the content was inset into the page
outset: Gives the appearance that the content was raised from
the page
border-width
The size of the border for each side. See Chapter 5.
border (Shorthand)
The border shorthand property accepts up to three values representing
border-width, border-style, and border-color.
fieldset {
border: 1px solid rgb(100,100,200); /* set all 4 borders */
Chapter 8: Backgrounds and Borders 137
border-radius
border-radius was introduced in CSS3 to allow for rounded corners
by providing a radius for the roundness of each corner. Experimental
support is included in recent versions of Firefox and Safari by way of
vendor extensions and in Opera and the upcoming IE9 directly via the
border-radius property. To further complicate things, Firefox has a
slightly different order in addressing the individual corners of a block.
div {
width: 250px;
height: 150px;
border: 2px solid black;
-webkit-border-top-left-radius: 30px;
-webkit-border-top-right-radius: 6px;
-webkit-border-bottom-right-radius: 30px;
-webkit-border-bottom-left-radius: 6px;
-moz-border-radius-topleft: 30px;
-moz-border-radius-topright: 6px;
-moz-border-radius-bottomright: 30px;
-moz-border-radius-bottomleft: 6px;
border-top-left-radius: 30px;
border-top-right-radius: 6px;
border-bottom-right-radius: 30px;
border-bottom-left-radius: 6px;
}
138 The CSS Pocket Guide
Figure 8.6
border-radius
set independently
on each corner.
Figure 8.7
Example of mixed
border styles.
Outline
Outlines are a special visual property that behave similarly to borders
but take up no space in the layout. Outlines are used most often to show
focus on a link, active form eld, or other element. They can also be
Chapter 8: Backgrounds and Borders 139
outline-color
The color of the outline.
outline-style
Uses the same style keywords as border does, with the addition of the
keyword auto, which is mapped to a device default outline style (or
solid).
outline-width
The width of the outline.
outline (Shorthand)
The outline shorthand property accepts up to three values representing
outline-width, outline-style, and outline-color:
:focus {
outline: 3px auto blue;
}
This section is not just about re-creating the effects of the border-radius
property, but it also demonstrates the use of many of the background
properties that are used earlier in the chapter.
If you have the exibility, break visual element into two groups
those that are important for conveying a sites branding, aesthetic,
or emotion, and those that would only reinforce that aesthetic. Then
pick your solution accordingly. Rounded corners on sidebars, headers,
callouts, and featured elements may be important enough to make
it necessary to have them work in the largest number of browsers.
Buttons, form elements, thumbnail images, and other content may
fall into that other bucket where it would be nice to have rounded
corners, but if they were squared off, it would be OK, too.
The same goes for other effects such as box shadows or color gradi-
ents (Chapter 14), which can be mimicked using background images.
Figure 8.8
One background
used to simulate
rounded corners.
a.button {
display: block;
width: 150px;
height: 20px;
padding: 2px 8px;
text-align: center;
color: #fff;
background: #666 url(images/1_part_corner.png) no-repeat;
}
a.button:hover,
a.button:active {
color: #00f;
}
[...]
<a class="button">fixed size button</a>
Figure 8.9
Two backgrounds
used to simulate
rounded corners.
div {
width: 236px;
padding: 8px;
background: #fff url(images/2_part_corner_bottom.png)
no-repeat bottom;
}
h3 {
margin: -8px -8px 0; /* push back out to edge of
container */
padding: 8px;
min-height: 19px;
background: url(images/2_part_corner_top.png) no-repeat
top;
}
[...]
<div>
<h3>top of box</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing
elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua.</p>
</div>
This method is quite easy to implement and maintain, and the pattern of
having one xed dimension occurs often in columns, sidebars, and rounded
Chapter 8: Backgrounds and Borders 143
buttons. There are two drawbacks: First the longer (bottom) image can be
required to be quite large if it needs cover an unknown amount of content,
and second the bottom image can bleed through the outside of the
corners of the top element if the outside of the corners is transparent.
Four Corners
In Chapter 6, while learning about absolute positioning, you saw an
example (refer to Figure 6.1) that took four small boxes and placed them
into each corner of their parent element. You can use this pattern to
create hooks to attach background images to, representing each of the
four corners. Though this method has more overhead than previous
methods and requires some added markup, the results are more exible
than other solutions. Figure 8.10 combines the four positioned corners
with a background image sprite.
Figure 8.10
Four backgrounds
used to simulate
rounded corners.
div {
position: relative;
width: 20%;
padding: 8px;
background: #CCC;
} (continues on next page)
144 The CSS Pocket Guide
.corner {
position: absolute;
padding: 0;
width: 14px;
height: 14px;
background-image: url(images/4_part_corner_sprite.png);
}
.ctl {
top: 0;
left: 0;
background-position: top left;
}
.ctr {
top: 0;
right: 0;
background-position: top right;
}
.cbr {
bottom: 0;
right: 0;
background-position: bottom right;
}
.cbl {
bottom: 0;
left: 0;
background-position: bottom left;
}
[...]
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing
elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua.</p>
Chapter 8: Backgrounds and Borders 145
Using JavaScript to add these four corner elements into the HTML
t ip
DOM on the y is a useful way to keep presentational elements out of
your markup and keep your code lean, especially if you are rounding multiple
different blocks on a page.
Drawing Pixels
Taking the positioning of empty elements to an extreme, you can create
1x1 boxes and meticulously re-create the pixels that draw the corners of
a containing block. This can allow for visual tricks such as anti-aliasing
and changing border radius without having to re-create background
image les, but it also makes for lots of code and markup overhead.
Like with the earlier four corners solution, you can use JavaScript to
create, plot, and position these extra elements, giving them proper
background-color. An example of this method is implemented in the
Curvy Corners JavaScript library (http://www.curvycorners.net/), which
uses the border-radius property in the CSS document to draw in the
rounded corner when loaded in a browser that doesnt already support
border-radius.
In times past, choosing type styling for a web site meant picking from
one of a handful of typefaces; setting a size, color, and a few other prop-
erties; and relinquishing the control that designers are used to when
designing for other media. CSS provides more control over font styling
and typesetting than many people realize, and in the last few years there
have been huge advancements in tools, services, and embeddable fonts
based on changes in CSS3.
This chapter explores how to choose the font used and discusses the
other properties that give you control over the appearance and the read-
ability of the text on the pages you build.
148 The CSS Pocket Guide
Font Basics
The typeface used for rendering text and its particular characteristics
such as size and weight are dened using font and its related properties.
font-family
The font-family property accepts a comma-separated list of font family
names. The rst value in the list that is installed on the device used to
read the page is the font that will be used to style the text.
h1 {
font-family: Does Not Exist, Arial, sans-serif;
}
In the previous code, the font name would be checked; if the font Does
Not Exist is not available, the next font Arial would be looked for, and so
on, until the generic family sans-serif was matched and used. In some
cases, font names vary a bit between Windows and Mac, so both names
would be listed, like so:
p {
font-family: Palatino Linotype, Palatino; /* Windows
Version, Mac Version */
}
font-size
The font-size property controls the size of the text in the element and
may be dened as a xed size or a size relative to the font size of the
parent element. Browsers set a default size based on settings in the user
preferences, commonly 16px.
<length>: A length measurement
Relative and percentage font sizes are based on their parent elements
computed font size. The effect of this behavior may be compounded
when nesting elements. The following sample (Figure 9.1 on the next
page) demonstrates how font sizes are calculated for nested elements.
150 The CSS Pocket Guide
body {
font-size: 96px;
}
li {
font-size: 0.5em;
}
[...]
<body>body: 96px
<ul>
<li>li: 0.5em = 48px
<ul>
<li>li: 0.5em = 24px
<ul>
<li>li: 0.5em = 12px
</li>
</ul>
</li>
</ul>
</li>
</ul>
</body>
Figure 9.1
Repeated
calculation of
half the parents
font size.
Chapter 9: Typography and Web Fonts 151
If this compounded calculation of the font size is not the desired behav-
ior, it may be more useful to set the font size on some container element
and avoid setting it on list items, paragraphs, or inline elements that
may appear in various locations in the HTML document. For the previous
example, the following would ensure that all items in the outer container
element (ul) are half the body size and that this value is not reapplied for
nested lists:
body > ul {
font-size: 0.5em;
}
Keeping It Relative
There is an eternal debate among web developers about whether it
is better (more accessible to those with poor eyesight) to use relative
font sizes on a page or whether it is OK to use a xed-size unit like
pixels. Much of the anti-xed-size argument is centered on the text-
zoom behavior of Internet Explorer 6 and older in which the browser
will not enlarge xed-sized fonts.
Even if the base font size you choose is a xed size (say 12 pixels), it
may be worthwhile to use relative units for any individual element-
specic or section-specic font size changes. Doing this allows for
changing the base font size while maintaining the scale and relative
sizes for headers, block quotes, footnotes, and so on, without the need
to edit each individual font-size property throughout the style sheet.
152 The CSS Pocket Guide
font-weight
The font-weight property controls the weight, or thickness, of the char-
acters in a font.
normal | bold: Keywords representing normal weight type (default)
and bolded type
bolder | lighter: Sets a weight relative to the weight inherited from
the parent element
100 to 900: A nine-step scale, in increments of 100, ranging from thin
(100) to black (900)
font-variant
Some typefaces are designed with several variant character sets, includ-
ing a set of small caps shapes. The font-variant allows selection of this
alternate set of characters.
normal: Selects the normal variant of a font face (default).
small-caps: Selects the small caps variant of a font face. If none exists,
small caps are simulated.
font-style
The style of the font is declared using the font-style property.
normal: Normal, upright, type (default).
line-height
The line-height property denes the height of each line of text (line
box). Leading, or vertical spacing between each line, is created by specify-
ing a line-height that is larger than the content height (font-size).
normal: A reasonable default value specied by the browser;
commonly 1.2
<number>: A numeric multiplier applied to the font size to calculate the
line-height
font (Shorthand)
The font shorthand property allows for assigning the indi-
vidual font properties (font-style, font-variant, font-weight,
font-size/line-height, font-family) in the same place. Note that
although most shorthand properties allow for individual property values
to be left out and assume the default or inherited value, at minimum
font-size and font-family must be declared. Also, the value of the
line-height property must be paired with the font-size value in the
format of font-size/line-height, such as 1.2em/1.4.
vertical-align
The vertical-align property sets the alignment of text (or other inline
content) in relation to the line box controlled via line-height. Because
this property controls the positioning of an inline element in relation to
a line box and not a block element, it is not suitable for aligning block
elements in a layout grid. The default value of baseline creates an align-
ment where the bottom of the characters in each inline element on a
line all start at the same position. The following are commonly used
values for vertical-align (Figure 9.2):
baseline: Aligns the baseline of the box with the parent elements
baseline
sub: Creates a subscript by lowering the baseline of the box
p {
font-size: 20px;
vertical-align: baseline;
color: #666;
background: #eee;
}
sup {
font-size: 1em;
vertical-align: super;
}
Chapter 9: Typography and Web Fonts 155
sub {
font-size: 1em;
vertical-align: sub;
}
span {
font-size: 0.6em;
}
[...]
<p>Baseline xyx <sup>xyx Sup <span>xyx</span></sup> xyx
Baseline <span>xyx</span> <sub>xyx Sub <span>xyx</span>
</sub> xyx Baseline</p>
Figure 9.2 Line boxes and vertical alignment with original baseline in black and
baselines for sub and super in gray.
text-decoration
You can set underlines, strikethrough, or other text decorations (yes, even
blink) via the text-decoration property. These decorations are drawn
separately from borders and are applied only to text.
underline: Each line of text is underlined.
text-transform
The text-transform property controls the capitalization of text. This can
be a useful property for reinforcing the formatting of navigation, buttons,
and headers.
capitalize: The rst character of each word is forced to be uppercase.
word-spacing
You can adjust the default space between each word in a string of inline
text using word-spacing.
<length>: A xed dimension used as an adjustment to the default
amount of space between words.
normal: No adjustment is made (equivalent to 0).
Chapter 9: Typography and Web Fonts 157
letter-spacing
The letter-spacing property controls the spacing of each character
in a word. Like word-spacing, the letter-spacing property denes an
adjustment to the default spacing for the font.
<length>: A xed dimension used as an adjustment to the default
amount of space between letters.
normal: No adjustment is made (equivalent to 0).
text-align
Horizontal alignment of text inside a containing block is dened by the
text-align property.
justify: The lines of text are ush with both sides of the box, adjust-
ing the spacing in between words as needed.
white-space
This property sets how the whitespace and newlines in an element are
calculated.
normal: Lines of text are wrapped to ll each successive line box with
text; sequences of whitespace (multiple space, tab, or newline charac-
ters) are collapsed (default).
pre: Text is considered to be preformatted in the source markup docu-
ment and whitespace, including newline characters, remains intact
(default for <pre> element).
nowrap: Whitespace is collapsed as normal, and all text is forced to the
same line.
word-wrap
In addition to setting the behavior for whitespace, with word-wrap you
can allow browsers to break lines in the middle of words to prevent long
strings of characters from overowing a box.
break-word: Allows a browser to place a break within a word to
prevent a long word with no whitespace characters from overow-
ing the box; words are broken by character, not syllables, and are not
hyphenated.
normal: Single words cannot be broken (default).
text-indent
The text-indent property denes an indentation for the rst line of text
in a block.
<length>: A xed measurement for the indentation
text-shadow
The text-shadow property introduced in CSS3 allows for one or more
<shadow> effects to be applied to the text of an element. This shadow
is drawn around the letters themselves, rather than around the outer
edges of the box like with box-shadow (Chapter 14).
none: No text shadow is applied.
h2 {
text-shadow: rgba(0,0,0,0.5) 2px 2px 5px;
/* transparent black shadow shifted right 2 and down 2 with
a 5px blur */
}
You can create the appearance of embossed text by mixing light and
dark text-shadow effects, as is done in this multiple-shadow example:
h2 {
text-shadow: rgba(0,0,0,0.3) 0 -1px, rgba(255,255,255,0.3) 0
1px;
}
Multiple shadows on the same element are drawn front (rst shadow
listed) to back (last shadow).
160 The CSS Pocket Guide
In 2006 I wrote a blog post outlining the use of a generic test le that
contained a wide variety of HTML elements that could be included
into the rst page you build or could be used in a style guide or
inventory document (http://placenamehere.com/article/178/). I still
use this tag test document for most sites I work on and have placed
the code in a project on GitHub (http://github.com/placenamehere/
PNHTagTest).
Both types of tools allow for early adjustment and review of a sites
styling and typographic choices and help create a great baseline
with which to build the rest of the site elements.
Chapter 9: Typography and Web Fonts 161
Specifying Typefaces
The choice of font and the availability of font faces can be some of the
most challenging aspects of web design. Theres a reason that most sites
youll visit appear in Times New Roman, Verdana, or Arial, and that is
because there just arent that many quality fonts installed on enough
computers to be reliable options for web designers. Some of that has
changed over time, and in the following sections Ive outlined a few ways
to select typefaces for use on the Web.
System Fonts
Operating systems such as Windows, Mac OS X, Linux, iOS, and Android
typically are bundled with a set of preinstalled fonts. Some extremely
common applications such as Microsoft Ofce install additional font les.
There are no truly ubiquitous fonts for the Web, because even the most
common fonts can be disabled or removed by the computers owner,
but these are some of the most commonly available fonts on desktop
browsers:
Serif typefaces: Times New Roman, Times, Georgia, Palatino Linotype
(Palatino on OS X)
Sans-serif typefaces: Verdana, Arial, Arial Narrow, Arial Black, Helvetica,
Impact, Trebuchet MS, Tahoma
Monospace typefaces: Courier New, Courier, Andale Mono, Lucida
Console
162 The CSS Pocket Guide
Font Embedding
To break free of the short list of commonly installed set of safe fonts,
IE4 introduced font embedding in CSS via the @font-face rule. With its
standardization by the W3C and more recent adoption by other browser
vendors, font embedding is gaining traction, but it is not without the
issues that come with early adoption of any technology.
@font-face
The @font-face rule allows for dening a custom font family and linking
that family to a resource or resources where the font le data resides.
Two sets of values are set with this rule:
font-family: The family name for the custom font; used to refer to the
font-family property later in the style sheet
src: The font source URI and optional (but in practice, suggested) font
format
Chapter 9: Typography and Web Fonts 163
@font-face {
font-family: "Chris Script";
src: url(fonts/ChrisScript.ttf);
}
h1 {
font-family: "Chris Script", cursive;
}
If a browser did not support the @font-face rule (or could not nd or did
not understand the particular format of the font), it would ignore the
rst font name when it tried to follow the font-family rule for the <h1>
element and render the element using the browser-dened cursive font.
A font that may appear on the system can be searched for by font name
using one or more local() values before the url(). This prevents the
need to download a copy of a font that might be installed on some
computers, but its not ubiquitous enough to be relied on or considered
safe for use without embedding.
@font-face {
font-family: "Vera Sans Mono";
src: local("Bitstream Vera Sans Mono"),
url(fonts/BSVSM.ttf);
}
h2 {
font-family: "Vera Sans Mono", "Courier New", cursive;
}
If the family name specied in the @font-face rule exists already either
by a previous rule or because it is on the users system, the new deni-
tion will take its place.
164 The CSS Pocket Guide
Font Formats
Like the HTML5 video wars (http://diveintohtml5.org/video.html), those
attempting to implement embeddable web fonts have to untangle a
mess of le format support among the various browsers. And like the
video format landscape, browser vendors have chosen to support differ-
ent font formats because of a mix of licensing and protection issues, plat-
form norms, and legacy behavior. Possible formats include the following:
truetype: TrueType fonts (TTF); supported in Safari 3.1+, Chrome 4+,
Firefox 3.5+, Opera 10+
opentype: OpenType fonts (OTF); supported in Safari 3.1+, Chrome 4+,
Firefox 3.5+, Opera 10+
embedded-opentype: Embedded Open Type (EOT) embeddable fonts;
supported in IE 4+
svg: SVG-based font denition; supported in Opera 10+, Mobile
Safari
woff: Web Open Font Format embeddable fonts (WOFF); supported
in Firefox 3.6+, IE 9+
From IE4 to IE8, Microsoft supported only the proprietary EOT format out
of concern that embedding TTF or OTF fonts required the raw font les to
be posted to a web server for the world to download and because doing
so would break the licensing agreements covering most fonts. The WOFF
was established in 2010 as a standard format for embeddable fonts that
addresses the piracy issues.
Until WOFF is widely supported, to embed custom fonts in IE and the rest
of the browsers, you must provide the font in at least two formats and
dene them similar to the following example.
Chapter 9: Typography and Web Fonts 165
@font-face {
font-family: "Vera Sans Mono";
src: url(fonts/BSVSM.eot);
src: local("Bitstream Vera Sans Mono"),
url(fonts/BSVSM.ttf) format("truetype");
}
For further discussion of offering multiple font format options, see Paul
Irishs article Bulletproof @font-face syntax (http://paulirish.com/2009/
bulletproof-font-face-implementation-syntax/).
The font-embedding techniques in the previous section are the new kids
on the block and arent free from implementation issues such as browser
support or font licensing, so these older and tested techniques are useful
to have in your arsenal.
As with text set directly into an <img> tag, these techniques can be
useful in small doses such as for article headings or navigation elements,
but replacing large blocks of type on the y provides a good deal of over-
head or maintenance problems.
Image Replacement
Rather than use an image tag to display non-HTML-based text, with
image replacement, you can use that same image le as a CSS-based
background on a more conventional HTML element. After sizing and
positioning the background image, the foreground text must be hidden
from the user by shifting its position, changing its display value, or doing
some similar trick. In the following example (Figure 9.3 on the next
page), headers are presented with the Bitstream Vera Sans font with
some embossed effects that cannot be accomplished with CSS- and
HTML-based type:
h2 {
display: block;
height: 25px;
background-image: url(images/sprite_imagereplace.png);
background-repeat: no-repeat;
text-indent: -9999px; /* shift HTML text out of view */
}
#hdrHome {
width: 80px;
background-position: 0 0;
} (continues on next page)
168 The CSS Pocket Guide
#hdrBlog {
width: 63px;
background-position: -88px 0;
}
#hdrPortfolio {
width: 107px;
background-position: -158px 0;
}
#hdrAbout {
width: 83px;
background-position: -272px 0;
}
[...]
<h2 id="hdrHome">Home</h2>
<h2 id="hdrBlog">Blog</h2>
<h2 id="hdrPortfolio">Portfolio</h2>
<h2 id="hdrAbout">About</h2>
Figure 9.3
Image
replacement for
headings.
Image replacement is a handy tool if used sparingly and for text that
will not change often. The techniques major drawback is that it is fairly
inexible and requires images (or an image sprite as in the previous
example) to be generated for each piece of text being replaced or edited.
Chapter 9: Typography and Web Fonts 169
Like sIFR, this requires turning the font into a new format (here, an
SVG-based font) and then using a JavaScript-based tool to read in the
HTML page as it loads and replace the designated elements with a new
rendering component.
This page intentionally left blank
10
All content types t into one of two display typesinline and block.
Almost. It may be obvious after thinking about it that tables with their
columns, rows, headers, and spanning cant quite be modeled by arrang-
ing a series of block elements, but lists with numbering or bullets also
need some special tools.
172 The CSS Pocket Guide
Lists
HTML list elements (<ul> and <ol>) are simple block elements. Individual
list items (<li>), too, are sized and positioned with the same box model,
with dimensions, padding, margins, and borders behaving as expected.
However, each item needs some extra parts to get the markers both
positioned properly and designated or incremented properly.
display: list-item
The default display value for a list item is list-item, allowing for the
rendering of the box containing the list item marker in addition to the
normal block behavior for the list item content.
list-style-type
You set the type of marker for a list item via the list-style-type
property. You can use a plethora of keywords as types; they account for
everything from the static bullet commonly used for unordered lists to
numeric and alphanumeric values for different languages and counting
systems. The following are some of the more commonly used types for
English-language sites:
disc | circle | square: Common glyphs; all items in the list will show
the same glyph (unless changed explicitly).
decimal | decimal-leading-zero: Decimal numbers starting with
1 or 01, respectively.
lower-roman | upper-roman: Lowercase and uppercase roman numerals.
list-style-image
The list-style-image property takes a <uri> for an image that
when specied replaces the generated list marker dened by the
list-style-type property.
list-style-position
The list-style-position property denes where in relation to the
list items box the list marker is positioned. Typically a marker will be
positioned outside the content area of the item out into the left gutter;
however, it can also be positioned inside of the list item, behaving as an
inline element at the beginning of the item would.
outside: The list marker acts an inline element positioned outside the
box generated by the items contents (default).
inside: The list marker is positioned inside the list items box.
Figure 10.1
Three list items
with markers
positioned
outside, with
the latter three
positioned inside.
174 The CSS Pocket Guide
Backgrounds as list-style-image
A nonrepeating, properly positioned background image on a list
item is a common method to give control over precise positioning of
list marker images. The following code will achieve this behavior by
combining the pattern of using padding to make space for a back-
ground image, as shown a few times in Chapter 7, with turning off
the default list marker with list-style-type: none.
ul {
margin-left: 0;
padding-left: 0;
}
li {
margin-left: 0;
padding-left: 20px;
list-style-type: none;
background: url(fancydot.png) no-repeat 4px 4px;
}
list-style (Shorthand)
The list-style shorthand property allows for assigning the indi-
vidual list properties (list-style-type, list-style-position,
list-style-image) in the same place.
li { list-style: none; }
::marker Pseudo-element
CSS3 added a handy pseudo-element to access the list marker, both
dening and providing a way to change the styles and positioning of the
marker that isnt available through shifting or padding on the list item
or wrapping the content of a list item in another element, allowing inde-
pendent control of properties such as color and font-size:
<li><span>list content</span></li>
Generated Content
As is the case with list markers, it can sometimes be desirable to display
content that doesnt come from the HTML document. Generated content
is dened with the content property and then added to the document as
the content of the pseudo-elements ::before and ::after (and, eventu-
ally, ::marker).
content
The content property allows for a number of different types of content
that may be added to the selected pseudo-element, including the
following:
<string>: Text content for inserting into the element
a.help::after {
content: "(?)";
color: red;
background: yellow;
}
a.next::after {
content: url(images/right_arrow.png);
}
[...]
<p>Here is some text that contains a link to the <a class=
"help" href="http://example.com/help.html">help page</a>
and a link to the <a class="next" href="http://example.com/
next.html">next page</a></p>
The previous code adds an arrow image after any link to a next document
and then a question mark after any help link, as shown in Figure 10.2.
These two hints, or similar additions using the content property, are
examples of where presentational hints introduced through design would
be different from content that would normally be in the HTML source.
Figure 10.2 Example of generated content added after links with different
class attributes.
Counters
CSS counters provide the ability to create and use a count of elements of
a selected type in a document. Though it would be most useful to aid in
customizing item markers, counters arent limited to lists and can help
with document outline style presentations or other embellishments.
counter-increment
The previous species that the counter with a provided text label
(<identifier>) should be incremented when the element dened
by the selector is encountered in the document.
<identifier>: The counter to be incremented by 1
counter()
Inside the content property, the current value of a given counter can be
accessed with the counter() function:
counter(<indentifier>): Returns the value of the specied counter
counter-reset
<identifier>: Resets the specied counter to 0
The following code was used to generate Figure 10.3 and demon-
strates three presentation options that cannot be accomplished with
list-style-type in current browsers.
<ol>
<li>list item</li>
<li>list item
<ol>
<li>list item</li>
<li>list item</li>
<li>list item</li>
</ol>
</li>
<li>list item</li>
</ol>
<h4>Heading</h4>
<ol>
<li>list item</li>
<li>list item</li>
</ol>
<h4>Heading</h4>
Figure 10.3
Demonstration
of counters used
for generated
content.
180 The CSS Pocket Guide
Tables
Using tables for creating a layout grid is an outdated web design practice
that has generated a lot bad press for the HTML table element. Even if
that practice has gone the way of the dodo in most modern web devel-
opment, tables for tabular data are just as important as ever. The layout
of a tablewith its grid of cells, myriad of borders, and the ability for
cells to span rows or columnscalls for some special formatting proper-
ties not used for other elements.
The layout model for the table element calls for margins and borders on
the outside of the element to behave the same as other blocks and width
to be calculated similarly, but it incorporates a few additional proper-
ties to control the spacing and display of the containing cells and their
padding, spacing, and borders. The following code generates the table
shown in Figure 10.4:
table {
background: #ccc;
border: 5px dotted #000;
border-spacing: 10px;
}
td {
width: 20px;
line-height: 20px;
padding: 10px;
background: #fff;
border: 2px solid #000;
}
td[rowspan="2"] {
border: 10px solid #666;
}
Chapter 10: Lists and Tables 181
tr {
border-top: 10px solid #aaa;
}
[...]
<table>
<tr>
<td> </td> <td> </td> <td> </td>
</tr>
<tr>
<td rowspan="2"> </td> <td colspan="2"> </td>
</tr>
<tr>
<td> </td> <td> </td>
</tr>
<tr>
<td> </td> <td> </td> <td> </td>
</tr>
</table>
A tables
layout with padding
border-collapse
set to separate.
line-height
border-spacing
border (td)
table-layout
To maintain the integrity of the grid of cells, the content contained in
each cell has traditionally had some impact on the height of rows and
width of columns in a table, with the browser free to make adjust-
ments to provided dimensions. Even when a cell width is provided,
a large amount of text or a large image may make the cell larger. The
table-layout property allows for changing the method browsers use
to size and render a table.
auto: The width of the table and table cells is established and adjusted
as the content of each cell in the table is rendered, with the dimen-
sions provided by the CSS properties and adjusted for size or amount
of content (default).
fixed: The width of the table and the table cells do not rely on the
content but is determined only by the width of the table and columns,
allowing a browser to start rendering the table immediately.
border-collapse
separate: The borders of individual table cells are drawn as distinct
features and separated by some border padding. No other parts of
a table have borders (default).
collapse: The borders of the table and all parts of a table share the
same border on each side.
Chapter 10: Lists and Tables 183
Figure 10.5
A tables
layout with
border (tr)
border-collapse
set to collapse.
border (table)
border (td)
184 The CSS Pocket Guide
border-spacing
The border-spacing property provides the padding between borders of
table cells and takes two <length> values, rst for the horizontal spac-
ing and second for vertical spacing. If only one <length> is provided, it
applies to both sides.
empty-cells
In the separated borders model, cells without content (or cells set to
visibility: hidden) can have their borders and background styling
rendered or ignored.
show: Displays the borders and background of an empty cell (default)
vertical-align
Unlike block-level elements, the contents of cells can be vertically posi-
tioned inside of the cell.
top: The content of the cell is top aligned.
text-align
The text-align property behaves normally when applied to table cells
(see Chapter 9).
behavior of the various parts of a table. The three basic parts of a tables
display are the table, a row, and a cell.
table: A block-level element that generates the outer structure of
a table
table-row: A row containing cells
Beyond these core three values, there are display values for all the various
pieces of a table such as table body, caption, and column groups. The fol-
lowing code illustrates the various table-related values and their context:
Designing and styling forms and getting constant results across browsers
and platforms can be the most difcult part of web development.
elements will change. Even in the same browser, the appearances may
differ between Windows, Mac OS X, Linux, and mobile devices. Figure 11.1
shows the difference in appearance of a select elements on three differ-
ent devices.
Figure 11.1 Interaction with select element in Safari/Apple iPhone iOS4, Safari/Apple
iPad iOS3, and IE 8/Windows XP ( from left to right).
Something else that can be unique to form layouts is the need to juggle
the myriad of positioning and placement and states of the elements of
the form. Large elds, small elds, sets of elds, labels, and help or error
messages all need to be placed so that it is clear to the visitor what is
being requested from them. The grid that works for a standard-length
text input along with its label may not work for a collection of radio
buttons or a combination of inputs such as parts of a phone number or
city and state.
Chapter 11: Forms and User Interface Elements 189
Safari will draw native form controls (the bubbly look on OS X) even
t ip
when some styles are dened. Set a border on the element to force
it out of the native mode and into one that takes other styles such as color
or backgrounds.
Sizing
Form elements, like images, are inline replaced elements. For styling
purposes, it is best to think of them as rectangular boxes even when
theyre round radio buttons or made of multiple parts like le input
elds. When setting the height and width of a form element, youre
setting the dimensions on the outer box. What the eld inside that box
does to ll the space is out of your hands.
form input[type="text"],
form input[type="password"],
form input[type="file"],
form textarea {
-ms-box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
This goes for the other properties as well. Where would you apply a back-
ground color to a radio buttoninside the circle or outside and behind
the circle in the rest of the box? Is the line between the text space and
the little handle of a select element a border? How many backgrounds
and borders are there in a le input eld that is often represented as
something that looks like a text input plus a button? What about all
those new input types like sliders in HTML5?
These are the questions that give browser developers (and in turn web
developers) migraines.
For the most consistent appearance, you should probably avoid borders
and background colors and avoid background images for radio buttons
and check boxes. (Figure 11.2 showed examples of browser differences.)
On the other hand, you can do interesting things with borders, back-
ground colors, and background images for the other eld types. In the
next example, a background image on a text input is used to create the
feeling of depth (Figure 11.3). Ive added background color change when
the element is in focus for a highlight.
input[type="text"] {
padding: 4px;
width: 100px;
border: 1px solid #000;
background: #fff url(images/inner_shadow.png) no-repeat
left top;
}
input[type="text"]:focus {
background-color: #fff335;
}
Figure 11.3
A text input with
a background
image.
192 The CSS Pocket Guide
Here are a few examples of using CSS and JavaScript to work around
form styling limitations:
Replacing the varied looks of le inputs (see the example at
http://www.quirksmode.org/dom/inputle.html).
Using backgrounds for highly styled radio buttons and check
boxes (see the example at http://www.thecssninja.com/css/
custom-inputs-using-css).
Implementing new HTML5 input types using custom JavaScript-
based widgets such as sliders, date pickers, color pickers, and other
types that are part of HTML5 if the visitors browser doesnt sup-
port them (discussed at http://diveintohtml5.org/forms.html).
selecting the input eld directly. The following code will set the same
text color for all the text and form elements:
Though not supported in IE7 or earlier, this is a great use case for the
inherit value to explicitly tell form elements to inherit certain proper-
ties from their parents.
label.required {
font-weight: bold;
}
p.errorDetails,
label.invalid,
input.invalid, (continues on next page)
194 The CSS Pocket Guide
input:invalid {
color: red;
}
input[type=submit].disabled,
input[type=submit]:disabled {
background: #aaa;
color: #fff;
}
label {
display: block;
margin-top: 1em;
}
[...]
<fieldset>
<legend>Your Info</legend>
<label for="fname">First Name:</label>
Chapter 11: Forms and User Interface Elements 195
Figure 11.4
Form presenta-
tion with labels
above form
elements.
label {
display: block;
margin-top: 1em;
}
div.field {
float: left;
width: 50%;
}
[...] (continues on next page)
196 The CSS Pocket Guide
<fieldset>
<legend>Your Info</legend>
<div class="field">
<label for="fname">First Name:</label>
<input type="text" name="fname" id="fname">
</div>
<div class="field">
<label for="lname">Last Name:</label>
<input type="text" name="lname" id="lname">
</div>
<div class="field">
<label for="phone1">Phone Number:</label>
<input type="text" name="phone1" id="phone1" size="3">
<input type="text" name="phone2" id="phone2" size="3">
<input type="text" name="phone3" id="phone3" size="4">
</div>
</fieldset>
Figure 11.5
A two-column
form layout.
Although including the input eld element inside the label tag is
note
valid HTML and doing so might allow for easier styling in this scenario,
this is considered a bad practice because of accessibility concerns.
Chapter 11: Forms and User Interface Elements 197
label {
float: left;
clear: left;
width: 150px;
margin: 0 10px 0 0;
padding: 0;
text-align: right;
}
input {
margin: 0 0 1em 0;
}
Figure 11.6
Labels to left of
form elements.
label,
span.label {
float: left;
clear: left;
width: 150px;
min-height: 1em; /* keep empty span open */
margin: 0 10px 0 0;
padding: 0;
text-align: right;
}
[...]
p label,
input[type="radio"]+label { /* reverse baseline label style */
float: none;
width: auto;
margin: 0;
}
[...]
<fieldset>
<legend>Questionnaire</legend>
<div class="field">
<span class="label"></span>
<input type="radio" name="chooseOption"
id="chooseOption[1]" value="1">
<label for="chooseOption[1]">Option One</label>
<input type="radio" name="chooseOption"
id="chooseOption[2]" value="2">
<label for="chooseOption[2]">Option Two</label>
Chapter 11: Forms and User Interface Elements 199
</div>
<p>
<input type="checkbox" name="agree" id="agree">
<label for="agree">Do you agree to this site's Terms of
Service?</label>
</p>
</fieldset>
Figure 11.7
Labels for radio
buttons and
check boxes.
Conditional Fields
Sets of conditional eldsif one option is chosen to display or enable
other optionstypically have states managed by JavaScript, but each
state is dened via classes such as the disabled class used in the next
code block. The script would move the disabled class around as the form
elements are changed.
fieldset.disabled {
display: none; (continues on next page)
200 The CSS Pocket Guide
}
[...]
<form action="#" method="get">
<div>
<label for="chooseOption[1]">Option One:</label>
<input type="radio" name="chooseOption"
id="chooseOption[1]" value="1">
<fieldset class="extra disabled">
<label for="option1extra">Extra Info for Option One
</label>
<textarea name="option1extra" id="option1extra"></textarea>
</fieldset>
</div>
<div>
<label for="chooseOption[2]">Option Two:</label>
<input type="radio" name="chooseOption"
id="chooseOption[2]" value="2" checked="checked">
<fieldset class="extra">
<label for="option2extra">Extra Info for Option Two
</label>
<input type="text" name="option2extra" id="option2extra">
</fieldset>
</div>
</form>
fieldset.extra {
display: none;
}
Chapter 11: Forms and User Interface Elements 201
input[type="radio"]:checked+fieldset.extra {
display: block;
}
Placeholder Text
A fairly common convention with text inputs is to place a small hint into
the eld. Doing this with the value attribute of the element can be prob-
lematic (causing the submission of the hint text or other oddities), so
HTML5 introduces the placeholder attribute. To accomplish this without
either attribute, you can create a second label element using JavaScript
and position it with CSS over the text input eld (as deconstructed in
Figure 11.8).
Figure 11.8
Deconstructing a
label covering the
input area of a
text eld.
Making Buttons
Getting users to interact with a site and share their information is the
primary purpose of any form, and for web apps or web-based promo-
tions, clicking the submit button may be the entire reason for the sites
existence. As such, submit buttons scream to be styled in ways that draw
the user to them. There are 101 different methods to enhance buttons;
this section offers a quick overview of the parts behind them.
A key hurdle to easy, exible button styling is that buttons are just
one HTML element, and there is only so much that can be done to one
element. You cant manufacture extra hooks for styling like you saw in
the rounded corner examples and elsewhere in this book, so youre stuck
202 The CSS Pocket Guide
with what is there (though perhaps you could wrap the button in some-
thing or use generated content in interesting ways).
Background Images
Background images can do a lot for a button: add depth, add the look of
ready to press and depressed states, and create many other effects that
a mix of color and border alone cannot do.
Submit button sizes are typically exible to allow for a wide range of text
lengths or font sizes. A xed-size button paired with a single nonrepeat-
ing background image can lead to text escaping the boundaries of the
graphic. With controlled button labels or a large enough button style
providing leeway for these cases, the xed width and height is possible.
Otherwise, stick with repeatable patterns and borders used to mark the
sides of the element.
Links As Buttons
Links are often interchangeable with submit buttons in a sites design.
The call to action may sometimes be associated with a form but often
not. Choose a class to use for links that should be styled similarly to
Chapter 11: Forms and User Interface Elements 203
button actions, and style both together in your code. And while youre
at it, dont forget the different states for each or the other types of
button elements (the button element as well as the button input type).
Figure 11.9 (on the next page) shows three different clickable HTML
elements styled similarly.
input[type="submit"],
button,
a.button:link, a.button:visited {
font: 12px/16px Arial, sans-serif; /* for input */
padding: 2px 0.5em;
color: #333;
background-color: #aaa;
border: 2px inset #aaa;
text-decoration: none; /* for link */
}
a.button:link, a.button:visited { /* fix some apparent box
model differences */
padding-top: 3px;
padding-bottom: 3px;
}
input[type="submit"]:hover, input[type="submit"]:focus,
button:hover, button:focus,
a.button:hover, a.button:active {
color: #000;
background-color: #999;
}
input[type="submit"]:disabled,
button:disabled,
a.button.disabled { (continues on next page)
204 The CSS Pocket Guide
color: #fff;
background-color: #ccc;
border-color: #ccc;
border-style: solid;
cursor: default;
}
[...]
<input type="submit" value="input">
<a class="button" href="#">link</a>
<button>button</button>
<input type="submit" value="input disabled"
disabled="disabled">
<a class="button disabled" href="javascript:void(0)">link
disabled</a>
<button disabled="disabled">button</button>
Figure 11.9
Links, input
buttons, and
button elements
styled similarly.
12
Media: Printing and
Other Devices
Media Types
User agents are categorized by their features, or the features of the
device theyre running on, into one of several media types. In some cases,
such as a desktop browser with a print preview feature, the user agent
can support multiple media types; however, only one type will be active
at any given time.
In practice, your typical web project will have styles targeting the media
types all, screen, print, and often handheld, while the other types will
be left to manage with the styling dened in the all type or will be left
to the default appearance.
Chapter 12: Media: Printing and Other Devices 207
You may nd the other types useful in niche projects. For example, if
youre designing slides for distribution on the Web after your presenta-
tion, then you may have a presentation specically targeting projected
media (which is triggered in Operas full-screen mode). For more on this
idea, as well as information on Operas support of the projection media
type, read Till Halbachs article Creating Presentations/Slideshows with
HTML & CSS at http://dev.opera.com/articles/view/html-css-slideshows/.
<html>
<head>
<!-- stylesheets for all media -->
<link rel=stylesheet type=text/css src=global1.css>
<link rel=stylesheet type=text/css media=all
src=global2.css>
<style type=text/css>[...]</style>
<style type=text/css media=all>[...]</style>
(continues on next page)
208 The CSS Pocket Guide
@import Rule
Like the designation of media types for link elements, external CSS les
included via the @import rule can be restricted to specic media types.
<style type=text/css>
/* stylesheets for all media */
@import url(global1.css);
@import url(global2.css) all;
@media Rule
The @media rule is used to specify that a subset of rules in a block of CSS
code should apply only to the supplied media types. As with the media
attribute of the <style> element, any code where @media rules are found
Chapter 12: Media: Printing and Other Devices 209
has already been downloaded. This rule is most useful for targeting
devices with small amounts of CSS.
Although you can have an @import rule inside a linked style sheet or an
@media rule inside either type of linked style sheet document, it is not
legal to nest an @media rule inside another @media rule. If you were to
dene a media type with @media or @import inside an already restricted
block of code, the new media type would further restrict the targeted
media list.
210 The CSS Pocket Guide
Print Media
The printed page, while having many similarities to the screen, differs in
many ways as well, most notably that the contents of a document are
split across multiple xed-sized pages rather than one single continuous
viewport. The properties listed in this section help control the presenta-
tion of each of those pages by offering guidelines about where those
page breaks occur within the documents content.
page-break-inside
The page-break-inside property allows for the restriction of page
breaks inside a given elements content.
auto: The user agent determines when it is appropriate to place a page
break inside an elements content (default).
avoid: This tells the user agent to avoid page breaks within the
elements content.
For all the page break properties, the page breaks may be unavoidable,
for example when a single element is larger than a single page. The
Chapter 12: Media: Printing and Other Devices 211
value avoid will cause browsers to attempt not to generate a page break,
however, and as the name avoid implies, it is just an attempt and not
an absolute rule.
Browser support for the page break properties is quite mixed, and
some browsers have more complete support for individual values than
others. You can nd a good breakdown and notes on support for the
page breakrelated properties at the Sitepoint CSS Reference (http://
reference.sitepoint.com/css/pagedmedia) or at the Mozilla Developer
Center (https://developer.mozilla.org/en/CSS_Reference).
Print Considerations
The presentation, width, color schemes, navigational elements, and other
design features of many web pages may be appropriate for the screen,
but not as much when printed. If someone is printing out an article,
recipe, or event information from your web site, the last thing they are
looking for is half the rst page taken up by navigation and advertis-
ing and an extra page at the end taken up with nothing but the footer
content and repeated navigation links.
To prepare pages for print, a few types of styles are often changed to
provide the best printed experience (and not waste your visitors paper
or ink).
Hide the sidebar, navigation, or other site meta elements that are
presented on the screen to help when interacting with the site on
the screen. Branding elements, logos, and legal information are still
212 The CSS Pocket Guide
The Print Preview option from your favorite browser will display with any
style sheet targeting the print media type and is a great way to test your
changes to the print presentation without wasting reams of paper.
@media print {
a:link::after,
a:visited::after {
content: ( attr(href) ) ;
color: #666;
font-style: italic;
Chapter 12: Media: Printing and Other Devices 213
}
}
Mobile Media
Handheld and mobile devices typically have small physical screens
(even as they have increasingly higher resolutions). They also have
slightly different interaction models such as touchscreens or heavily
keyboard- or tab-based movement.
Mobile Considerations
The smaller screen and slower connection typical of handheld devices are
key factors in mobile web development and may drive a less is more
approach to these devices.
The slower connection speed and cost of transferring data on some
mobile plans can make it desirable to rely more on the default browser
style sheet than you would in a screen context.
The touch interface on many smartphones and tablets may drive
the need for links and buttons to appear larger, and the spacing
between items should be clear to avoid fumbling ngers pressing
the wrong item.
Feature phones, unlike smartphones, offer a limited subset of CSS and
a limited layout capability or canvas size. Display and navigation on
these devices can also be very linear (left to right, top to bottom), so
the positioning and complex element layouts may be ignored.
214 The CSS Pocket Guide
Media Queries
New in CSS3, media queries add a syntax for describing the characteris-
tics and features of the device being used to view a page, allowing for
more precise control or better targeting of those features that might
be why you provide one set of styles over another. The following code
demonstrates how to target a handheld device in landscape orientation
(wider than it is tall):
As shown in the previous examples, you can combine media features into
a more complex description using the and keyword. You can use the not
Chapter 12: Media: Printing and Other Devices 215
The only keyword does not logically impact the result of the media query
expression; however, it creates a value for the media attribute so that
browsers that do not support media queries cannot parse into a common
media type they support and thus can be used to hide styles from these
browsers.
Media Features
The following is a list of media features for which you can specify in a
media query expression.
Since the chances that you will have declared the precise viewport width,
measured to the pixel (or ems or other <length> unit), is quite slim, you
can specify the width feature as a min-width or max-width. This holds
true of the other features where specied.
width: The width of the viewport or page box; accepts min- and
max- prexes.
height: The height of the viewport or page box; accepts min- and
max- prexes.
Responsive Design
In Chapter 7 you learned about building xed and exible layout grids
as well as setting limits on exible layouts by using the min-width and
max-width properties. You can use these techniques to make adaptive
layouts that nd a compromise between the best presentation and read-
ability of the content and the visitors browser dimensions.
But what if you could adapt the layout from the standard two-column
layout into a one-column layout for narrower browsers or bring the
footer up into a third column for the insanely wide screens? Or what if
you could adjust the size of header type or swap background images
Chapter 12: Media: Printing and Other Devices 217
For an in-depth review of media queries and how you can use them to
design pages that adapt not just to media but also to other browser
scenarios, see Ethan Marcottes article Responsive Web Design
(http://www.alistapart.com/articles/responsive-web-design/ ).
Browser Support
Media queries are currently supported in Safari 3+, Firefox 3.5+, Opera 7+,
Internet Explorer 9+, mobile WebKit, and Opera Mobile. Therefore, there
is wide support for them, except for IE 6 through IE 8s large chunk of the
desktop market.
It isnt so bad, though, because the support (or lack thereof) can be taken
into consideration as just another device criteria in many instances. For
mobile development, youre most likely putting handheld device types into
two or three buckets alreadyrst specifying the most devices and then
breaking smartphones by screen size or orientation. The following example
shows a baseline style sheet going to all handhelds and then using media
queries with more specic style sheets for those more capable devices:
You can take the same approach for sites meant for the desktop. Code
the base style sheet with the appropriate baseline layout grid, font sizes,
and other measurements and serve it to all screen media using the
media type declaration. Then use media queries to provide enhance-
ments to those base styles and make a richer or cleaner experience
around the edge cases using responsive design patterns.
But often, the task of building a web site does not start with rebuilding
all elements from scratch; instead, it often starts with reusing elements
by drawing from a library of code youve previously written or open
source code for libraries or elements that you can use.
220 The CSS Pocket Guide
CSS Resets
In the Chapter 2 discussion of browser- and user-created style sheets, you
saw how the default styling for common elements such as paragraphs,
links, and forms can be different from each other. Building a site on this
inconstant foundation can make cross-browser consistency a more dif-
cult task than it already is.
A CSS reset creates a common baseline to work from and zeros out some
or all aspects of browser default styling. For example, it is common for
browsers to have padding set on the <body> element so that plain HTML
content has a little room to breathe. However, it may be easier to style
a site if you are instead starting exactly the top-left corner. Font sizes,
padding, margin, table properties, and form elements are all typical
candidates for being reset.
Using Resets
It is common to include a reset le so it is the rst CSS code that the
browser encounters. This is done by inserting its contents into the begin-
ning of the main style sheet for the web site, by referencing it directly
using a <link> element before your global style sheet, or by using an
@import statement at the beginning of the main style sheet le, similar
to the following:
@import url(reset.css);
There isnt much to a reset, but a few solid examples have evolved over
the years. Theyre written to normalize inconsistencies between the
default setting of various browser or trimming down default rules when
theyre too overbearing (as in the case of form elements). Whichever one
you use, look it over before you use it on a project to make sure it isnt
doing anything you dont want (such as setting colors or font sizes).
Chapter 13: Resets and Frameworks 221
HTML5 Reset
The HTML5 Reset from Richard Clark (http://html5doctor.com/html-5-reset
-stylesheet/) builds on the Eric Meyers Reset and makes some modica-
tions to sync with new or deprecated elements in the HTML5 specication.
Not resetting in the rst place means not having to re-create common
styles like those for emphasis, list indentation, and bullets that were
already set by the browser. Also, edge cases or little-used HTML elements
(<dl>, <cite>, <legend>) and markup patterns (<ul> in a <blockquote>)
must be tested to make sure that content added to the site later is prop-
erly styled.
222 The CSS Pocket Guide
The type of content appearing on the site will weigh heavily on the
appropriateness of a reset. A text-heavy site such as a blog may want
to leave more of the browser styling intact, while an application or
e-commerce site that relies on smaller content elements may want to be
more controlled. Ultimately, the choice to zero out styles at the begin-
ning of a projects code is one of taste and how you prefer to work rather
than one of purely technical merit.
When the included library loads, it will typically test the browsers
support against a list of CSS features. If a feature is supported, the script
will do nothing. However, for those unsupported features, it will comb
the style sheet code for their use and then attempt to replicate the
behavior of the unsupported CSS through scripting.
You can use JavaScript to check for all CSS 2.1 or CSS3 features missing
in a browser, and other libraries are written to target specic gaps in
support.
IE7.js
The goal of IE7.js (http://code.google.com/p/ie7-js/) is to make Internet
Explorer 5.5 and 6 behave like and support the features of Internet
Explorer 7. This includes xing some HTML and CSS bugs as well as
adding support for alpha-transparent PNG images. This may seem like a
baby step, but if IE7 is among your target browser matrix and your code
is already stable there, you may not need to do more than this to get IE6
in line.
IE8.js and IE9.js scripts are also part of the project, by Dean Edwards,
providing similar version bridging support (to match IE8 and IE9,
respectively).
Selectivzr
Keith Clarks ie-css3.js (http://selectivizr.com/) is an example of a project
that aims to add missing selector support (::first-child, ::nth-child(),
[attr], and so on) to Internet Explorer 6 through 8. It remains lightweight
by leveraging other JavaScript libraries already included in the document,
such as jQuery or MooTools, that have selector tools.
eCSStender
Aaron Gustafsons eCSStender (http://ecsstender.org/) provides a exible
framework for all browsers for xing browser bugs or lack of support as
well as helping navigate the tangle of vendor extension usage in more
modern browsers. Extensions are available that add support for CSS3
features such as transitions, transforms, and rgba()/hsla() colors in
older browsers.
Modernizr
Unlike the previous libraries mentioned, Modernizr (http://www
.modernizr.com/) does not itself add support for any missing feature
224 The CSS Pocket Guide
When there are just a few features that would have to be xed in this
manner, it may be more efcient to nd alternate ways to code the
effects through CSS and HTML rather than turn to scripting. There may be
other selectors you can use, for example. In browsers with lower usage, it
may be OK just to leave things unsupported.
Chapter 13: Resets and Frameworks 225
Likewise, if you are tasked with building a site where you know you have
older browsers in that A- or B-grade classication (Chapter 2), you proba-
bly will want to avoid some of the unsupported selectors or cutting-edge
CSS3 features while building the site. This will ensure that your targets
are met and your site displays properly, even without JavaScript enabled,
in the largest segment of your user base.
These bridge libraries are best when you have a few noncore elements
of the design youd like to see supported in a wider space or when youre
looking to help out the lower-grade browsers that youd still like to
deliver the full experience to.
CSS Frameworks
With so many millions of sites being designed each year, it is a good
assumption that any new project that comes along will have a layout
grid or other layout properties that may have already been built for
another site. Perhaps there are details or contexts of content items that
will be unique, but patterns will emerge from the layout grid or other
areas that can be transferred from one project to another.
These frameworks include not only a style sheet but also HTML markup
patterns and examples for accomplishing common tasks such as a
layout grid.
Blueprint
Blueprint (http://www.blueprintcss.org/) provides a broad starting point
for starting to build a site including a reset, layout grid tools, and base-
line typographic and form styling. There are also plug-ins or examples for
common content elements such as tabs, buttons, and iconography.
960
The 960 grid system (http://960.gs/) takes a 960-pixel area and allows
you to specify a 12- or 16-column grid with 20-pixel gutters between
them. This split, and the code that is generated and provided for you
to place content in the grid, allows you to quickly put a page layout
together. The sizing and spacing rules offer a very controlled grid to
design a site from without being too restrictive.
YUI Library
The Reset le I mentioned earlier is just a small part of the YUI Library.
The larger project is comprised of a baseline set of CSS les , baseline
JavaScript les, and components for common web application interface
components such as cookie access, drag-and-dropped elements, date
pickers, and sliders. Similar interface widget libraries are available from
jQuery UI, script.aculo.us, and MochaUI. They all provide a collection of
widgets to choose from and rules for embedding and skinning those
content elements, but they do not offer the more general reset and
framework aspects that YUI does.
For instance, the YUI tools tend to be a bit more web application focused,
and OOCSS works best when the site is complex enough to have the
depth of content types to manage. Attempting to go against the grain
will cause you to write more code than what youd save and will cause
you more headaches than starting from scratch.
Beyond Frameworks
Frameworks provide a starting point to begin developing a web site,
but they dont change how you write and edit CSS code. All the rules of
inheritance, specicity, source order, and syntax discussed in this book
continue to apply for any site-specic code you add on top of a chosen
framework.
228 The CSS Pocket Guide
CSS Preprocessors
To turn the written code back into code in a syntax, browsers understand
a conversion layer (preprocessor) is added as a compilation step via tools
on your local development machine or via server-side scripts.
Less
Less (http://lesscss.org/) is a Ruby gem that adds the ability to include
the CSS rules from one selector into another (a mixin), selector nesting,
simple mathematical formulas, and variables that stand in for values
so that colors, sizes, and other values need to be typed only once. The
following is an example of both a variable denition and a nested rule
as written using Less:
@highlight_color: #eaa;
blockquote {
font-size: 1.4em;
a {
text-style: italic;
background-color: @highlight_color;
}
}
Chapter 13: Resets and Frameworks 229
The previous code gets compiled into the following nal code that gets
sent to the visitors browsers:
blockquote {
font-size: 1.4em;
}
blockquote a {
text-style: italic;
background-color: #eaa;
}
Sass
Sass (http://sass-lang.com/) is also a Ruby gem and offers variable, mixin,
math, and nesting features similar to Less. It has two different syntaxes
to choose from, one similar to CSS (and Less) and an alternate syntax that
breaks from the brackets and colons of CSS into a tab-based style some
may nd more readable or manageable.
This page intentionally left blank
14
The Not Too Distant
Future of CSS
For example, the need to use multiple HTML elements as hooks so that
multiple background images can be used (shown in Figure 7.4), and the
frequency with which this is done, has led to CSS changes that support
multiple background images on a single element, as you saw in Chapter 8.
232 The CSS Pocket Guide
This chapter will give you a look at other new properties you can use
today as well as what is to come. In some cases, these features have
much less support in current browsers than the features covered
elsewhere. Included in this chapter is information on current browser
support for each property to help you make an informed decision about
which of these properties have wide enough support to nd their way
into your projects. Check the already mentioned browser support charts
or When Can I Use (http://caniuse.com/) for detailed and current
browser support information before deciding whether to use each
property.
The description of a CSS <shadow> has three parts: two to four <length>
values, a shadow <color>, and an optional inset keyword. The <length>
values represent, in order, the horizontal offset of the shadow, the verti-
cal offset of the shadow, the blur distance (0 is no blur), and a spread
Chapter 14: The Not Too Distant Future of CSS 233
Figure 14.1
Example of a box
shadow without
and with a blur
radius.
div.one {
/* for Firefox */
-moz-box-shadow: 10px 10px rgba(0,0,0,0.8);
/* for Safari and Chrome */
-webkit-box-shadow: 10px 10px rgba(0,0,0,0.8);
/* W3C specs */
box-shadow: 10px 10px rgba(0,0,0,0.8);
}
div.two {
/* for Firefox */
-moz-box-shadow: 10px 10px 20px rgba(0,0,0,0.8);
/* for Safari and Chrome */
-webkit-box-shadow: 10px 10px 20px rgba(0,0,0,0.8);
/* W3C specs */
box-shadow: 10px 10px 20px rgba(0,0,0,0.8);
} (continues on next page)
234 The CSS Pocket Guide
[...]
<div class="one">
Box with a sharp drop shadow
</div>
<div class="two">
Box with a drop shadow with a large blur
</div>
Shadows can be draw inside an element using the inset keyword in the
denition of a shadow. Replacing the inside shadow made with a back-
ground image used on the text input eld in Figure 11.4 can be done with
the following code (Figure 14.2):
div.one {
/* for Firefox */
-moz-box-shadow: inset 10px 10px rgba(0,0,0,0.8);
/* for Safari and Chrome */
-webkit-box-shadow: inset 10px 10px rgba(0,0,0,0.8);
/* W3C specs */
box-shadow: inset 10px 10px rgba(0,0,0,0.8);
}
div.two {
/* for Firefox */
-moz-box-shadow: inset 10px 10px 20px rgba(0,0,0,0.8);
/* for Safari and Chrome */
-webkit-box-shadow: inset 10px 10px 20px rgba(0,0,0,0.8);
/* W3C specs */
box-shadow: inset 10px 10px 20px rgba(0,0,0,0.8);
}
[...]
<div class="one">
Box with a sharp inset shadow
</div>
Chapter 14: The Not Too Distant Future of CSS 235
<div class="two">
Box with a inset shadow with a large blur
</div>
Figure 14.2
Example of an
inset box shadow
without and with
a blur radius.
auto: Scales the side of the image so that the inherent aspect ratio of
the image is maintained; if both values are auto, the image appears at
its normal size (default).
<percentage>: Scales the size of the background image to a percent-
age of the elements (not images) background area in the specied
direction.
<length>: Scales the side of the background image to the specied
length.
div.one {
background: url(images/background_sizing_tile.png)
no-repeat top left;
}
div.two {
background: url(images/background_sizing_tile.png)
no-repeat top left;
/* for Firefox 3.6 */
-moz-background-size: 100% 50px;
/* for Safari and Chrome */
-webkit-background-size: 100% 50px;
/* for Opera */
-o-background-size: 100% 50px;
/* W3C specs */
background-size: 100% 50px;
}
div.three {
background: url(images/background_sizing_tile.png)
no-repeat top left;
Chapter 14: The Not Too Distant Future of CSS 237
Figure 14.3 Example of a background image without background-size set and with
background-size set to specic dimensions.
238 The CSS Pocket Guide
Figure 14.4 displays the background-size property when set using these
keywords.
div.one {
background: url(images/background_sizing_tile.png)
no-repeat top left;
}
div.two {
background: url(images/background_sizing_tile.png)
no-repeat top left;
/* for Firefox */
-moz-background-size: cover;
/* for Safari and Chrome */
-webkit-background-size: cover;
/* for Opera */
-o-background-size: cover;
/* W3C specs */
background-size: cover;
}
Chapter 14: The Not Too Distant Future of CSS 239
div.three {
background: url(images/background_sizing_tile.png)
no-repeat top left;
/* for Firefox */
-moz-background-size: contain;
/* for Safari and Chrome */
-webkit-background-size: contain;
/* for Opera */
-o-background-size: contain;
/* W3C specs */
background-size: contain;
}
[...]
<div class="one">
Background with no background sizing
</div>
<div class="two">
Background with background-size set to cover
</div>
<div class="three">
Background with background-size set to contain
</div>
Color Gradients
The background property is getting another enhancement with a feature
that allows for the denition of a color <gradient> value to take the
place of a more conventional le-based background-image.
Color gradients are lighter weight and more exible than attempting to
create the properly sized gradient via an image le in Photoshop or other
graphic creation tool. Gradients can be linear or radial and can optionally
transition between one or more color stops.
The following code builds a linear gradient that shifts from solid black to
solid white and then back to black (Figure 14.5):
div {
[...]
/* for unsupported browsers */
background: #aaa;
/* for Firefox */
background: -moz-linear-gradient(top, #000, #fff, #000);
/* for Safari and Chrome */
background: -webkit-gradient(linear, left top, left
bottom, from(#000), to(#000), color-stop(0.5,#fff));
/* W3C specs */
background: linear-gradient(left top, #000, #fff, #000);
}
The direction (or angle) of the gradient can be controlled, as can the
distance it takes to transition colors.
Chapter 14: The Not Too Distant Future of CSS 241
Figure 14.5
A linear gradient
with three colors.
Border Images
Flexible, image-based borders can replace the standard border styles
using the border-image property. This is achieved by slicing the border
area into a nine-segment grid representing each of the corners of the
border area and the sides, as shown in Figure 14.6. A single image le is
similarly split into nine segments and mapped to each of the areas of the
border area and the center of the container.
Figure 14.6
An example
of the nine-
quadrants of
an image used
for a border
background.
242 The CSS Pocket Guide
border-image-source
The border-image-source property accepts a reference to the image
used as the border image.
border-image-slice
border-image-slice denes where the four lines that slice an image
into segments are positioned, inset from each of the four sides of the
image. For the image displayed in Figure 14.6, it would make sense to
position these dividing lines 30 pixels from each edge to create nine even
segments. The distance from each edge can be measured by the follow-
ing values:
<number>: The number of pixels (or the coordinates for SVG images).
Pixel units are implied for bitmap background images, and the unit
should be left off.
<percentage>: A percentage value based on the dimensions of
the image.
div.one {
/* for Firefox */
-moz-border-image-slice: 30 / 30px 15px;
/* for Safari and Chrome */
-webkit-border-image-slice: 30 / 30px 15px;
/* W3C specs */
border-image-slice: 30 / 30px 15px;
}
border-image-repeat
The border-image-repeat property denes how the slices of the border
image ll the exible space on the side borders and middle portion of
the border area. You can use one or two of the following keywords:
stretch: The image slice is scaled to t the available space, without
repeating (default).
repeat: The image slice is not scaled but tiled to ll the available
space. As a result, the image may appear cropped on some edges.
round: The image slice is tiled; however, only whole images are used.
The tiles are then scaled evenly to ll the remaining space.
If only one keyword is provided, it is applied to both the borders and the
center section.
border-image (Shorthand)
The shorthand border-image accepts the previous three subproper-
ties, as well as the additional properties of border-image-width
244 The CSS Pocket Guide
Figure 14.7 uses the image from Figure 14.6 as a border image and
demonstrates the difference between border-image-repeat values.
div {
/* set common width for all browsers */
border-width: 30px;
}
div.one {
/* for Firefox */
-moz-border-image: url(images/border_background_tile.png)
30 30 30 30 round round;
/* for Safari and Chrome */
-webkit-border-image: url(images/border_background_tile.png)
30 30 30 30 round round;
/* W3C specs */
border-image: url(images/border_background_tile.png) 30 30
30 30 round round;
}
div.two {
/* for Firefox */
-moz-border-image: url(images/border_background_tile.png)
30 30 30 30 stretch stretch;
/* for Safari and Chrome */
-webkit-border-image: url(images/border_background_tile.png)
30 30 30 30 stretch stretch;
/* W3C specs */
border-image: url(images/border_background_tile.png) 30 30
30 30 stretch stretch;
Chapter 14: The Not Too Distant Future of CSS 245
}
[...]
<div class="one">
border image with sides and middle set to round
</div>
<div class="two">
border image with sides and middle set to stretch
</div>
Figure 14.7
Examples of
border back-
grounds with
round and
stretch values
for border-
image-repeat.
WAI-ARIA Roles
Though not explicitly CSS related, the Accessible Rich Internet Application
(WAI-ARIA) specication (http://www.w3.org/TR/wai-aria/) provides
denitions of common semantics of application widgets and states as
a semantic layer to be added to existing HTML markup using the role
attribute. Role types include navigation, progressbar, alertdialog,
tab, and tooltip. By applying these roles to HTML elements, screen
readers and other assistive devices can react to these items more appro-
priately than they would an element with a class or id of progressbar.
246 The CSS Pocket Guide
The CSS attribute selector can also leverage these role denitions, along
with state-based attributes such as aria-checked, as hooks for styling,
rather than relying on class attributes.
You can nd more about WAI-ARIA roles and their usage in the spec on
the W3C site (http://www.w3.org/TR/wai-aria/usage).
Figure 14.8
A exible,
multicolumn
layout using
calc( ).
In the previous code, the available width of the container is split shared
by the margins between the boxes (the four vertical side borders), with
the remaining area split evenly between the two exible columns. The
arithmetic you would use to calculate what is left over after the xed
area is 100% 10px 4px. That area split between each column and
cleaned up a bit is 100%/2 14px/2.
transform
The transform property is used to dene one or more
<transform-functions> for the specied element.
/* for Firefox */
-moz-transform: rotate(270deg);
/* for Safari and Chrome */
-webkit-transform: rotate(270deg);
/* for Opera */
-o-transform: rotate(270deg);
/* W3C specs */
transform: rotate(270deg);
}
In the previous code example, the element was rotated and then posi-
tioned with absolute positioning to properly place it (Figure 14.9 on the
next page). The position before the rotation (and thus in any browser
that doesnt support transitions) is shown by the dotted outline.
250 The CSS Pocket Guide
Figure 14.9
The ag and text
content is rotated
by 270 degrees
to a vertical
position.
Figure 14.10
The ag and text
content is rotated
and translated,
leaving a
more desirable
nontransformed
state.
Chapter 14: The Not Too Distant Future of CSS 251
transform-origin
The origin for any transform is by default the center of the element (50%
50%). You can adjust this origin using the transform-origin property,
allowing for rotation around a different point. transform-origin accepts
two values: the rst is the horizontal position of the element, and the
second is the vertical position. Fixed units such as px units, negative
values, and values greater than 100 percent are all accepted, allowing for
the point of origin to be moved outside the element. Also accepted are
keywords for dening the origin point, including left, center, and right
along the x-axis and top, center, and bottom along the y-axis.
Figure 14.11
Elements
rotated around a
transform origin.
The diagonal
arrow represents
the new position
of the origin; the
circle represents
the rotational
transform.
For the sake of brevity, only the code targeting Firefox is displayed in
note
the following code.
div {
height: 50px;
width: 50px; (continues on next page)
252 The CSS Pocket Guide
The CSS3 transform property, its values, and the transform-origin prop-
erty are supported in some form by Safari 3.2+, Chrome 3+, Opera 10.5+,
Firefox 3.5+, and Internet Explorer 9+.
Transitions
CSS transitions are a way to dene parameters for animating changes
to CSS properties on a specied element. Changes to styles can occur
because of updates in element state (:hover, :valid, and so on), scripted
changes to styles on an element, or other scripted changes to the DOM
structure causing a change in how selectors are applied.
transition-property
transition-property designates which CSS property or properties are
animated when a change occurs. Animations can occur with most CSS
properties; however, some properties such as background-image and
text-decoration cannot.
transition-duration
The time it takes to transition from the original value of a property to the
nal value can be set via the transition-duration property.
<time>: The time it takes for a transition to complete; in seconds
(s units)
transition-timing-function
By default the transition between values of a property is animated
along an even, linear function. You can alter this change via the
transition-timing-function by choosing between several built-in
functions or a custom cubic-Bezier curve.
ease | linear | ease-in | ease-out | ease-in-out: Keywords represent-
ing different types of built-in functions for animation
cubic-bezier(<number>, <number>, <number>, <number>): A transi-
tion function to dene a custom cubic-Bezier curve
transition-delay
You can add a delay before a transition using the translation-delay
property.
<time>: The time it takes before for a transition begins animating; in
seconds (s units)
transition (Shorthand)
The shorthand transition property accepts one or more groups of
transition subproperty groups in the order: <transition-property>
<transition-duration> <transition-timing-function> <transition-
delay>. The following code example denes the transform for the hover
state on an image and applies a basic easing animation to the transition.
Chapter 14: The Not Too Distant Future of CSS 255
img {
/* for Firefox 4 */
-moz-transition: -moz-transform 0.5s ease-out;
/* for Safari and Chrome */
-webkit-transition: -webkit-transform 0.5s ease-out;
/* For Opera */
-o-transition: -o-transform 0.5s ease-out;
/* W3C specification */
transition: transform 0.5s ease-out;
}
img:hover {
/* for Firefox 4 */
-moz-transform: scale(1.5, 1.5);
/* for Safari and Chrome */
-webkit-transform: scale(1.5, 1.5);
/* For Opera */
-o-transform: scale(1.5, 1.5);
/* W3C specification */
transform: scale(1.5, 1.5);
}
[...]
<img src="images/hover_me.png" width="90" height="90"
alt="Hover Me" />
CSS transitions are supported in Safari 3.2+ Chrome 3+, Opera 10.5+,
Firefox 4+, and Internet Explorer 9+.
Index
clearfix utility class, 115 Curvy Corners JavaScript library, 145, 224
code custom bullets, 128130
code examples for this book, xvii
CSS coding styles, 1520 D
writing CSS code, xviiixxii dashed keyword, 136
color data
with alpha transparency, 6466 data: URI scheme, 61
background color, 124, 125 tabular data, inputting (forms), 199
basics, 6264 The data: URI kitchen tool, 61
border-color property, 135 declaration blocks, 3
color gradiants, 240241 declarations/declaration blocks, 3
color palettes, 6768 descendant combinator, 4849
design and, 67 design
form controls and, 190191 clever design, 133
outline-color property, 139 color and, 67
text color, 64 responsive design (media), 216217
columns. See also multicolumn layouts developer tools, xxixxii
constraints, column design and, 121122 devices
faux, 106107 handheld, 213214
xed-sized, 117 user agents and, 12
exible, 119 dimensions, min and max in box model,
combinators, 4849 7475
combining selectors, 50 :disabled pseudo-class selector, 193194
comments, CSS code and, xix, 1720 display property, 8485
computed values, 7, 8 display:none property, 112
conditional comments, 2930 DOCTYPE switches, 2526
constraints, column design and, 121122 Document Object Model (DOM)
contain keyword, 238 JavaScript and, 15
containers documents, CSS code and, 1718
container elements, 88 DOM, JavaScript and, 15
containing blocks, 8991 dotted keyword, 135
escaping, 110111 drafts, of specications, 10
content drop-down menus, 111112
in CSS, 101, 102 duration of transitions, 254
generated, 175176, 212 dynamic pseudo-classes, 41
hiding, 112
content blocks, creating, 102104 E
content boxes, 81, 82
continuous media, dened, 1213 eCSStender, 223
corners. See rounded corners, faking Edwards, Dean, 223
counters (lists), 177179 elements
cover keyword, 238
basics, 9
Creating Presentations/Slideshows with element types for content display, 8485
HTML & CSS, 207 form elements. See form controls
CSS nested, font sizes and, 149151
basics, 12 nesting, 7577
code, writing, viiixxii overlapping in backgrounds, 130131
coding styles, 1520 required vs. optional embellishments, 140
CSS2, CSS 2.1, CSS3, 11 reusing. See resets
Index 259
H K
hacks, targeting browsers with, 2829 keywords. See also specic keywords
Halbach, Till, 207 background-repeat property and, 125
handheld devices, 213214 border-image-repeat property and, 243
hasLayout ag, 3032 border-style property, 135136
height properties, 70, 71, 153 color keywords, 63
hexadecimal color values, 62 font-family property, 148149
hidden keyword, 93 lists, 175
horizontal centering blocks, 8081 Koch, Peter-Paul, 27
:hover pseudo-class, 41 Korpela, Jukka, 27
hsla(h,s,l,a), color value, 65, 66
hsl(h,s,l), color scheme, 63 L
HTML, 8, 12, 1315 labels, 194195, 197, 199
HTML <link> element, 1314 Lamb, Iain, 160
HTML <style> element, 14 language pseudo-class, 43
html element, 108109 Last Call periods (LC), 10
HTML5 Reset, 221 last child pseudo-class, 4445
hue-saturation-lightness color scheme, 63 last of type pseudo-class, 45
hyperlinks, printing and, 212 left keyword, 93, 97
Less, 228
I letter-spacing property, 157
ID selector, 38 library, drop-in JavaScript, 3435
IE7.js, 223 licensing of fonts, 165166
images. See also background images line-height property, 153
border images, 241245 link pseudo-class selectors, 41
image replacement, 167169 links as buttons, 202204
list-style-image property, 173, 174 liquid layouts, 119
Increase Your Font Stacks With Font lists, 171179
Matrix, 162 ::before and ::after pseudo-elements,
inheritance, 78, 192193 175, 176
inline elements, 9 ::marker pseudo-element, 175
Internet Explorer (IE) counter( ) function, 177
bridge libraries and, 223 counters, 177179
conditional comments and, 2930 generated content, 175176
Developer Tools, xxi list items, 109110
hasLayout and, 3032 list properties, 172175, 177
Irish, Paul, 165 list-item default value, 172
ul, ol, and li, 172
J LoVe/HAte, 42
JavaScript
to add four-corner elements, 145 M
browser support and, 222225 Marcotte, Ethan, 217
drop-in libraries for browser support, margin property, 70, 7172
3435 margins, 7880, 94, 95
style sheets and, 15 max-width property, 121122
The JavaScript Pocket Guide, 111 measurements, 5860
media
mobile, 213214
print, 210213
Index 261
peachpit.com /creativeedge