html that targets print the previous one is now targeting screen: Using an @import rule Another way to attach target external style sheets is with @ import rules in the style eleme
Trang 1Finally, External Style Sheets
type="text/css"
This identifies the data (MIME) type of the style sheet as “text/css” (cur-rently the only option)
You can include multiple link elements to different style sheets and they’ll all apply If there are conflicts, whichever one is listed last will override previous settings due to the rule order and the cascade
Importing with @import
The other method for attaching external style sheets to a document is to import it with an @import rule in the style element, as shown in this exam-ple:
<head>
<style type="text/css">
@import url("http://path/stylesheet.css");
p { font-face: Verdana;}
</style>
<title>Titles are required.</title>
</head>
In this example, an absolute URL is shown, but it could also be a relative URL (relative to the current (X)HTML document) The example above shows that
an @import rule can appear in a style element with other rules, but it must come before any selectors Again, you can import multiple style sheets and
they all will apply, but style rules from the last file listed takes precedence over earlier ones
You can also use the @import function within a .css document to reference
other .css documents This lets you pull style information in from other style
sheets
Note
You can also supply the URL without the url( ) notation:
@import "/path/style.css";
Again, absolute pathnames, beginning at the root, will ensure that the css document will always be found.
You can try both the link and @import methods in Exercise 13-3
Modular Style Sheets
Because you can compile information from multiple external style sheets, modular style sheets have become popular for style management With this method, one external style sheet attached to an (X)HTML document accesses style rules from multiple .css files You can use this method strategically to
reuse collections of styles that you like to use frequently in a mix-and-match style with other collections
exercise 13-3 |
Making an external
style sheet
As noted in an earlier tip, it is common
practice to create an embedded style
sheet while designing a site, then to
move the rules to an external style
sheet once the design is finished.
We’ll do just that for the cabbages
style sheet.
Open the latest version of
cabbages.html Select and
cut all of the rules within the
style element, but leave the
<style> </style> tags, because
we’ll be using them in a moment.
Create a new text document and
paste all of the style rules Make
sure that no element tags got in
there by accident.
Save this document as cabbage.
css in the same directory as the
cabbage.html document.
Now, back in cabbage.html, we’ll
add an @import rule to attach the
external style sheet like this:
<style type="text/css">
@import url(cabbage.css);
</style>
Save the file and reload it in the
browser It should look exactly the
same as it did when the style sheet
was embedded If not, go back and
make sure that everything matches
the examples.
Delete the whole style element
and this time, we’ll add the style
sheet with a link element in the
head of the document.
<link rel="stylesheet"
type="text/css"
href="cabbage.css" />
Again, test your work by saving the
document and viewing it in the
browser If you want more practice,
try doing the same for the style
sheet for the Black Goose Bistro
online menu from Chapter 12,
Formatting Text
1.
2.
3.
4.
5.
Trang 2Style Sheets for Print (and Other Media)
For example, frequently used styles related to navigation could be stored in a
navigation style sheet Basic typography settings could be stored in another,
form styles in another, and so on These style modules are added to the main
style sheet with individual @import rules Again, the @import rules need to go
before rules that use selectors
Content of clientsite.css:
/* basic typography */
@import url("type.css");
/* form inputs */
@import url("forms.css");
/* navigation */
@import url("list-nav.css");
/* site-specific styles */
body { background: orange; }
more style rules
Style Sheets for Print
(and Other Media)
Colors and fancy backgrounds are nice for web pages, but they are often a
nuisance when the page is printed There has been a common convention on
the Web to provide a “printer friendly” version for pages that are
informa-tion-rich and likely to be printed The print version was usually a separate
(X)HTML document that was text-only, or at the very least, stripped of all the
bells and whistles, and reduced to a single column of content
Now that CSS is widely supported, you can make a version of the document
that is customized for print without having to make a separate (X)HTML
document It’s all handled with a separate style sheet that gets used only
when the document is sent to a printer
In fact, CSS2 introduced the ability to target “print” and eight other different
media types (see the CSS for Other Media sidebar) This is done using the
media attribute in the link element or a media keyword in an @import rule in
the style sheet
In this very simplified example, I’ve created a separate style sheet for the
cab-bage.html document that gets used when the document is printed This is the
contents of cabbage_print.css:
body {
margin-left: 10%;
margin-right: 10%; }
div#titlepage {
padding: 1em;
border: thin double black; }
CSS for Other Media
CSS2 introduced the ability to target style sheets to nine different media Currently, only screen, print, and
all are widely supported; however,
handheld is getting more attention The complete list is as follows:
all
Used for all media.
aural
Used for screen readers and other audio versions of the document.
braille
Used with braille printing devices.
embossed
Used with braille printing devices.
handheld
Used for web-enabled cell phones or PDAs.
Used for printing or print previews.
projection
Used for slideshow-type presentations.
screen
Used for display on a computer monitor.
speech
Introduced in CSS2.1 to eventually replace aural
tty
Used for teletype printers or similar devices.
tv
Used for presentation on a television.
For more information about media-specific style sheets, see the W3C pages at www.w3.org/TR/CSS21/
media.html.
Trang 3Style Sheets for Print (and Other Media)
a { text-decoration: none;}
div#titlepage p { text-align: center;
font-variant: small-caps; }
p { text-align: justify; }
h1,h2,h3,h4,h5,h6 { text-transform: uppercase;
text-align: center; } This print style sheet differs from the previous version in these ways: All color and background properties have been removed
A border has been added to the “titlepage” div to make it stand out Links are not underlined
Once the media-specific style sheets are created, I attach them to the source document and specify which style sheet is used for which media Here are two ways to do it:
Linking to media-dependent style sheets
•
•
•
Style Sheets
for Print
I highly recommend these articles
on print style sheets by Eric Meyer,
published by A List Apart The
articles document the details of
building a print style sheet for A List
Apart, and then building it again.
“CSS Design: Going to Print”
(www.alistapart.com/articles/
goingtoprint)
“ALA’s New Print Styles” (www.
alistapart.com/articles/
alaprintstyles/)
F U R t H e R R e A D I n G
Style Sheets
for Print
I highly recommend these articles
on print style sheets by Eric Meyer,
published by A List Apart The
articles document the details of
building a print style sheet for A List
Apart, and then building it again.
“CSS Design: Going to Print”
(www.alistapart.com/articles/
goingtoprint)
“ALA’s New Print Styles” (www.
alistapart.com/articles/
alaprintstyles/)
F U R t H e R R e A D I n G
Figure 13-22. What cabbage.html looks
like when printed The print-specific style
sheet removes the colors and puts a rule
around the “titlepage” div.
Use the media attribute in the link element to specify the target medium Here, I added a new link element to cabbage html that targets print (the previous one is now targeting
screen):
<head>
<link rel="stylesheet" type="text/css"
href="cabbage.css" media="screen" />
<link rel="stylesheet" type="text/css"
href="cabbage_print.css" media="print" />
</head>
Using an @import rule
Another way to attach target external style sheets is with @ import rules in the style element (or in another external style sheet):
<style type="text/css">
@import url(cabbage.css) screen;
@import url(cabbage_print.css) print;
</style>
You should already be pretty familiar with how this document looks in the browser Figure 13-22 shows how it looks when it
is printed
This is a very simplified example of what can be done with print style sheets For more information on this rich topic, see the Style Sheets for Print box
Trang 4Test Yourself
Test Yourself
This time we’ll test your background prowess entirely with matching and
multiple-choice questions
Which of these areas gets filled with a background color?
the area behind the content
any padding added around the content
under the border
the margin around the border
all of the above
a and b
a, b, and c
Which of these is not a way to specify the color white in CSS?
a #FFFFFF b #FFF c rgb(255, 255, 255)
Match the pseudoclass with the elements it targets
a a:link 1 links that have already been clicked
b a:visited 2 elements that are highlighted and ready for input
c a:hover 3 the first child element of a parent element
d a:active 4 a link with the mouse pointer over it
e :focus 5 links that have not yet been visited
f :first-child 6 links that are in the process of being clicked
Match the following rules with their respective samples shown in Figure
13-23 (right) All of the samples in the figure use the same source
docu-ment consisting of one paragraph eledocu-ment to which some padding and a
border have been applied
body {background-image: url(graphic.gif);}
p {background-image: url(graphic.gif); background-repeat: no-repeat;
background-position: 50% 0%;}
body {background-image: url(graphic.gif); background-repeat:
repeat-x;}
p {background: url(graphic.gif) no-repeat right center;}
body {background-image: url(graphic.gif); background-repeat:
repeat-y;}
body { background: url(graphic.gif) no-repeat right center;}
1
a
b
c
d
e
f
g
2
3
4
a
b
c
d
e
f
1
2
3
4
5
6
1
2
3
4
5
6
Trang 5Review: Color and Background Properties
Which rule will not work in Internet Explorer 6 and earlier (Windows) due to lack of support?
p.highlight:hover {background-color: yellow}
li:first-child {background-color: #CCCCCC;}
div#contents {background: url(daisy.gif) no-repeat fixed;}
blockquote: before {content: "%8220;"; font-size: x-large; color: purple;}
all of the above
Review: Color and Background Properties
Here is a summary of the properties covered in this chapter, in alphabetical order
background A shorthand property that combines background properties
background-attachment Specifies whether the background image scrolls or is fixed
background-color Specifies the background color for an element
background-image Provides the location of an image to use as a background
background-position Specifies the location of the origin background image
background-repeat Whether and how a background image repeats (tiles)
color Specifies the foreground (text and border) color
5
a
b
c
d
e
Trang 6IN THIS CHAPTER
The components of an
element box Setting box dimensions
Adding padding around content Adding borders Adding margins Assigning display roles
In Chapter 11, Cascading Style Sheets Orientation, I introduced the box
model as one of the fundamental concepts of CSS According to the box
model, every element in a document generates a box to which properties
such as width, height, padding, borders, and margins can be applied You
probably already have a feel for how element boxes work, from adding
back-grounds to elements This chapter covers all the box-related properties Once
we’ve covered the basics, we will be ready to move boxes around in Chapter
15, Floating and Positioning
We’ll begin with an overview of the components of an element box, then
take on the box properties from the inside out: content dimensions, padding,
borders, and margins
The Element Box
As we’ve seen, every element in a document, both block-level and inline,
generates a rectangular element box The components of an element box are
diagrammed in Figure 14-1 Pay attention to the new terminology—it will be
helpful in keeping things straight later in the chapter
Content area Padding area
Margin area
Outer edge Inner edge
width
height
Border
Figure 14-1 The parts of an element box according to the CSS box model.
THINKING INSIDE
THE BOX
(Padding, Borders, and Margins)
Trang 7Setting the Content Dimensions
content area
At the core of the element box is the content itself In Figure 14-1, the con-tent area is indicated by text in a white box
inner edges
The edges of the content area are referred to as the inner edges of the element box This is the box that gets sized when you apply width and
height properties Although the inner edges are made distinct by a color change in Figure 14-1, in real pages, the edge of the content area would be invisible
padding
The padding is the area held between the content area and an optional border In the diagram, the padding area is indicated by a yellow-orange color Padding is optional
border
The border is a line (or stylized line) that surrounds the element and its padding Borders are also optional
margin
The margin is an optional amount of space added on the outside of the
border In the diagram, the margin is indicated with light-blue shading, but in reality, margins are always transparent, allowing the background of the parent element to show through
outer edge
The outside edges of the margin area make up the outer edges of the ele-ment box This is the total area the eleele-ment takes up on the page, and it includes the width of the content area plus the total amount of padding, border, and margins applied to the element The outer edge in the dia-gram is indicated with a dotted line, but in real web pages, the edge of the margin is invisible
All elements have these box components; however, as you will see, some prop-erties behave differently based on whether the element is block or inline In fact, we’ll see some of those differences right off the bat with box dimensions
Setting the Content Dimensions
Use the width and height properties to specify the width and height (natu-rally) of the content area of the element You can specify the width and height only of block-level elements and non-text inline elements such as images The
width and height properties do not apply to inline text (a.k.a non-replaced) elements and will be ignored by the browser In other words, you cannot specify the width and height of an anchor (a) or strong element (see note)
The total width of an
element includes the width
of the content plus the
total amount of padding,
borders, and margins
applied to the element.
The total width of an
element includes the width
of the content plus the
total amount of padding,
borders, and margins
applied to the element.
Trang 8Setting the Content Dimensions width
height
By default, the width and height of a block element is calculated
automati-cally by the browser (thus the default auto value) It will be as wide as the
browser window or other containing block element, and as high as necessary
to fit the content However, you can use the width and height properties to
make the content area of an element a specific width Em, pixel, and
percent-age values are the most common ways to size elements
The width and height properties are straightforward to use, as shown in these
examples and Figure 14-2 I’ve added a background color to the elements as
well, to make the boundaries of the content area more clear
p#A {width: 400px; height: 100px; background: #C2F670;}
p#B {width: 150px; height: 300px; background: #C2F670;}
width: 150px; height: 300px;
width: 400px; height: 100px;
Figure 14-2. Specifying the width and height of paragraph elements.
The main thing to keep in mind when specifying the width and height is
that it applies to the content area only Any padding, border, and margins you
apply to the element will be added to the width value So, for example, if you
set the width of an element to 200 pixels, and add 10 pixels of padding, a
1-pixel border, and 20 1-pixels of margin, the total width of the element box will
be 262 pixels, calculated as follows:
20px + 1px + 10px + 200px width + 10px + 1px + 20px = 262
Note
Actually, there is a way to apply width
and height properties to anchors by forcing them to behave as block elements with the display property, covered at the end of this chapter.
Note
Actually, there is a way to apply width
and height properties to anchors by forcing them to behave as block elements with the display property, covered at the end of this chapter.
Maximum and Minimum Dimensions
CSS2 introduced properties for setting minimum and maximum heights and widths for block elements They may be useful if you want to put limits on the size of an element.
max-height, max-width, min-height, min-width
These properties work with block level and replaced elements (like images) only The value applies to the content area, so if you apply padding, borders, or margins, it will make the overall element box larger, even if a max-width or max-height
property have been specified.
Unfortunately, these properties are not supported by Internet Explorer
6 and earlier There there is a workaround for max-width that uses
a non-standard IE extension, which you can read about in this article
by Svend Tofte at www.svendtofte.
com/code/max_width_in_ie/ The css-discuss archive offers links to several min-width workarounds here: css-discuss.incutio.com/
?page=MinWidth.
Maximum and Minimum Dimensions
CSS2 introduced properties for setting minimum and maximum heights and widths for block elements They may be useful if you want to put limits on the size of an element.
max-height, max-width, min-height, min-width
These properties work with block level and replaced elements (like images) only The value applies to the content area, so if you apply padding, borders, or margins, it will make the overall element box larger, even if a max-width or max-height
property have been specified.
Unfortunately, these properties are not supported by Internet Explorer
6 and earlier There there is a workaround for max-width that uses
a non-standard IE extension, which you can read about in this article
by Svend Tofte at www.svendtofte.
com/code/max_width_in_ie/ The css-discuss archive offers links to several min-width workarounds here: css-discuss.incutio.com/
?page=MinWidth.
Trang 9Setting the Content Dimensions
This is the way it is documented in the CSS2 Recommendation, and the way
it works in all standards-compliant browsers (Firefox, Netscape 6+, Safari, Opera, and Internet Explorer 6 and 7 in Standards Mode) However, it is important to know that there is a well-known inconsistency in the way IE 5, 5.5 and 6 (in Quirks Mode) interprets width and height values See the IE/ Windows Box Model sidebar for details and a workaround
Note
Standards and Quirks Mode are covered
in detail in Chapter 10, Understanding
the Standards
Note
Standards and Quirks Mode are covered
in detail in Chapter 10, Understanding
the Standards
One of the most notorious browser inconsistencies is that
Internet Explorer for Windows (all versions except 6 and 7
running in Standards Mode) has its own implementation of the
box model.
In these versions, the width property is applied to the outer
edges of the borders, not to the content area as established
in the CSS Recommendations This causes major discrepancies
between how the element is sized in standards-compliant
browsers and how it will appear in IE/Windows.
Take the div from an earlier example that has its width set
to 200 pixels, with a 20 pixel margin, a 1 pixel border, and 10
pixels of padding On standards-compliant browsers, the visible
element box would measure 222 pixels (200 + 2 + 20), and the
entire element box including the margin would be 262 pixels
But IE 5 and 5.5 (Windows only) applies the 200px width value
to the outer edges of the borders (see Figure 14-3 ) The padding
and border are subtracted, leaving a content area that’s 178
pixels wide The outer edges of the element box would measure
218 pixels, not 262 You can see how this would present a
problem in page layouts with precisely sized columns or page
widths.
border
Content
Margin
Padding
W3C box model
Border box model (IE, 5.5 and 6 in Quirks mode)
width: 200px;
Figure 14-3 Box model interpretation in WinIE 5 and 5.5.
To deal with these discrepancies, the first thing to do is make sure you use a proper DOCTYPE declaration to ensure IE 6 and
7 (the vast majority of IE traffic as of this writing) will switch into Standards Mode and display the element widths as you’d expect.
If for some reason you must support IE 5 and 5.5, you can use
a conditional comment to direct an IE 5/5.5-specific style sheet containing adjusted width values to just those browsers Other browsers will interpret the contents as a regular comment and ignore it, but IE versions are programmed to pay attention to what’s inside.
In this example, the IE5/5.5 style sheet contains a rule that sets the width of the div to 222 pixels When IE 5/5.5 subtracts the border and padding widths, the content area will end up 200 pixels wide, as desired
div { width: 222px; }
Name the style sheet clearly, such as ie5.css, or similar In the
real world, chances are this style sheet will have more than one rule, but we’ll keep this example simple.
Next, link that style sheet to the document, but contain the
link element in a conditional comment that calls on the special style sheet only “if the IE version is less than 6.”
<! [if lt IE 6]>
<link rel="stylesheet" type="text/css"
media="screen" href="/css/ie5.css" />
<![endif] >
Obviously, there’s more to it than I’ve covered here, so I encourage you to read more at these resources:
The Microsoft tutorial on conditional comments (msdn microsoft.com/workshop/author/dhtml/overview/
ccomment_ovw.asp) Conditional Comments article at Quirksmode.com (www quirksmode.org/css/condcom.html)
The IE/Windows Box Model
Trang 10Setting the Content Dimensions Specifying height
In general practice, it is less common to specify the height of elements It is
more in keeping with the nature of the medium to allow the height to be
cal-culated automatically, based on the size of the text and other contents This
allows it to change based on the font size, user settings, or other factors If you
do specify a height for an element containing text, be sure to also consider
what happens should the content not fit Fortunately, CSS gives you some
options, as we’ll see in the next section
Handling overflow
When an element is set to a size that is too small for its contents, it is possible
to specify what to do with the content that doesn’t fit, using the overflow
property
overflow
Figure 14-4 demonstrates the predefined values for overflow In the figure,
the various values are applied to an element that is 150 pixels square The
background color makes the edges of the content area apparent
Figure 14-4 Options for handling content overflow.
visible
The default value is visible, which allows the content to hang out over
the element box so that it all can be seen
hidden
When overflow is set to hidden, the content that does not fit gets clipped
off and does not appear beyond the edges of the element’s content area
The Future of the Box Model
CSS3 includes a new box-sizing
property that lets authors choose whether width and height dimensions are applied to the content area (as is the current model) or to the outer edges of the border (as implemented by IE 5/5.5) For a good overview of this new feature, read Peter-Paul Koch’s article
“Box Model Tweaking” at www.
quirksmode.org/css/box.html
The Future of the Box Model
CSS3 includes a new box-sizing
property that lets authors choose whether width and height dimensions are applied to the content area (as is the current model) or to the outer edges of the border (as implemented by IE 5/5.5) For a good overview of this new feature, read Peter-Paul Koch’s article
“Box Model Tweaking” at www.
quirksmode.org/css/box.html