1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Pro CSS Techniques- P4 docx

50 264 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề CSS Layouts
Trường học University of Third Faculty
Chuyên ngành CSS Layouts
Thể loại Chương
Năm xuất bản 2006
Thành phố Unknown
Định dạng
Số trang 50
Dung lượng 2,89 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Because a block-level element will take up 100 percent of the available width by default, thewrapper will stretch to fill whatever size the browser window is; there’s no need to specify

Trang 1

Figure 7-7. Problem solved!

If we resize the text somewhat, you’ll notice that the page reflows accordingly, as shown inFigure 7-8

Figure 7-8. Same page with resized text

Trang 2

The addition of the footer (admittedly, a footer with no actual content), which is thengiven the clear:both; CSS property/value pairing, solves the problem of the outer elementcollapsing underneath these floated items—but it’s including additional markup for the sake

of it, some might argue There are ways that you can avoid inserting seemingly superfluousmarkup like this and still manage floated items effectively, something which we cover later inthis chapter

The main issue with this fixed-width layout is still that it won’t allow text to resize pletely Eventually you’ll run out of horizontal room for the text So with that in mind, let’s look

com-at a more flexible CSS layout

The Liquid Layout

As its name suggests, a liquid layout is one that reflows to fill the available space Some people

swear by this layout as it gives the person viewing your site control (“I want my window thissize”) However, this layout has its own dangers:

• If the window is resized to maximum, reading large blocks of text can become difficult;

scanning from the end of a line to a new line is not easy

• If the window is sized down quite a lot, elements of the page may collapse in on eachother and overlap in all sorts of weird and not-so-wonderful ways if you don’t do yourmath correctly

In short, the flexibility that a liquid layout offers may come at a price, depending on howyour site visitors set their browsers But caveat emptor!

Here’s the CSS for a liquid layout of the same page design Rather than set a specific widthfor the wrapper container, we’ve specified a margin in the body element (40 pixels at each side)

Because a block-level element will take up 100 percent of the available width by default, thewrapper will stretch to fill whatever size the browser window is; there’s no need to specify

a width here

Trang 3

body {margin:10px 40px;

background:#dade75;

border:1px solid silver;

}

#header {background: #272727 url(header-bg.gif) repeat-x bottom left;

padding:10px 15px 10px 13px;

}

#content-wrapper {background:#fff url(nav-to-content-trans.gif) repeat-y left;

float:right;

width:75%;

}

#content-inner {padding:5px 15px 0 15px;

}See Figure 7.9 for the result, at various widths

Trang 4

Figure 7-9. Liquid layout at different sizes

The width of the navigation and the content add up to 100 percent (75 percent + 25 percent)

However, if you were to add a border to either of these elements (even a one-pixel border), youwouldn’t have enough room for the two elements to sit side by side, since they are floated Oneitem would wrap underneath the other (as shown in Figure 7-10) Try not to mix and match inthis way or, if you must, shave off the percentage values just a little—perhaps 24% and 74%—

and try resizing the screen to see what effect this has

Trang 5

Figure 7-10. Be careful when adding widths of floated items; if they add up to more than 100 percent, wrapping like this can occur.

Tip You may have wondered why we included both acontent-wrapperand acontent-inner div—why not just one container for the content? This is a simple workaround to a problem you’ll encounter whencalculating widths of elements, especially when using a flexible design When you’re adding padding to anarea, such as around the text in the main content,paddingadds to the widths you’ve defined and may takethe total over 100 percent It is often much less problematic to use an outer container on which you specifythe width, and then apply the padding, border, or margin properties on the inner container That way, theseproperties can work independently and won’t cause issues with calculating widths Purists might argue thatadding another divis a waste of markup, but we feel it is a minor inconvenience to make the CSS workcross-browser As long as you use sensible idattributes for these divs, it’s a highly practical compromise.The issue is related to how browsers understand the Box Model, which defines how the width of content in

a block-level element is calculated and rendered alongside borders, margins, and padding widths Earlierversions of IE got the calculation wrong, thus causing untold problems for cross-browser designs We dis-cuss the Box Model problem—and the hack that solves a lot of the problems associated with it—in Chapter 6(we also present a hack-less alternative)

Elastic Layouts

As you learned from the previous example, with the liquid layout the browser window is stretchedwide and the content becomes difficult to read What you really want is a page width that works

Trang 6

alongside the font size so that the two aspects are linked in some way If the font size is reduced,the line length—and along with it the page width—comes down accordingly, and vice versa.

Thankfully, there is a method for accomplishing this goal: the elastic layout

In an elastic layout, when you change the font size, other elements scale up or downaccordingly You use em measurements rather than pixels or percentages An em is directlyrelated to the size of the typeface, so if you specify a width for the wrapper in terms of ems,when you increase the font size the width of the wrapper goes up as well

The first step is to set a sensible baseline On most browsers, the default font size is 16 els If you can knock the default down to 10 pixels in the CSS for the body, calculations will be

pix-a lot epix-asier from thpix-at point on You cpix-an do this by setting font-size in the body to 62.5%

(62.5 percent of 16 = 10):

body {font-size:62.5%;

}Then, knowing that each em represents 10 pixels at the default font size, you can use emsfor subsequent measurements For example:

h1 {font-size:2em}

would give you level 2 headings of 20 pixels at the default font size, but these headings wouldscale up if the user prefers

Let’s look at the amended style sheet for the elastic layout As before, the HTML isunchanged; only the CSS is different The significant changes are highlighted in bold:

body {margin:0;

padding:10px 15px 10px 13px;

}

#content-wrapper {float:right;

background:#fff url(nav-to-content-trans.gif) repeat-y left;

Trang 7

}

#content-inner {padding:5px 15px 0 15px;

}The effect is best demonstrated with another comparative screen shot (Figure 7-11) Thisone shows the page in IE 6/Win set at the five font-size intervals available in the View ➤ TextSize menu

Figure 7-11. Elastic design in IE at five font sizes

Trang 8

The two-column widths scale up, as does the text content; the only item that does notscale up is the heading, as this is a fixed-width img element Given that, you could just as easilyuse scaling text for that area.

When Elastic Layouts Attack!

Predictably, there’s another gotcha to mention now An elastic layout is perhaps too helpful to

users What if they scale things up so much that the page doesn’t fit in the browser window?

Silly them, you might be tempted to say, but there will be times when you’ll want to take backsome control Here’s where a hybrid layout comes in

Elastic Layout: Constrained

In the constrained version—a slight tweak of the previous version—you use ems for sizing thetext and the widths of the wrapper, navigation, and content divs However, you stop them fromgrowing too big by setting a percentage for the max-width property For the wrapper div, let’s tellthe browser that the maximum it should go up is 95 percent of the browser viewport The navi-gation and content are constrained to 25% and 75%, respectively Here is the amended CSS:

body {margin:0;

Trang 9

#header {background: #272727 url(header-bg.gif) repeat-x bottom left;

padding:10px 15px 10px 13px;

}

#content-wrapper {float:right;

background:#fff url(nav-to-content-trans.gif) repeat-y left;

width:73%;

max-width:73%;

}

#content-inner {padding:5px 15px 0 15px;

IE 6 and earlier also don’t offer limitless scope for scaling fonts up like other browsers do, soyou probably don’t need to worry about this problem too much You aren’t likely to be able toscale the page design up so that it’s bigger than the browser window anyway

Figure 7-12 shows the web page at the default size, then notched up a bit in the secondscreen In the third screen, the width goes no further but the text scales up further within theupper boundaries that have been set

Trang 10

Figure 7-12. Elastic design with an upper width constraint

Trang 11

Tip Just as you can use the max-widthCSS property to set upper width constraints, you can also applylimits the other way using the min-widthproperty Try amending the code and see the effect for yourself.

Resolution-Dependent Layouts

An interesting technique that you might like to employ is the resolution-dependent layout.

(Actually, that’s a bit of a misnomer, as it’s not the resolution of your monitor but the size ofthe window in which you’re currently viewing a web site that we’re interested in.) With thistechnique, you display one view of your page as a default (normally a smaller window size)but for users who are viewing the site in a large window, you display an adapted design thatmaximizes that space available This layout is not the same as a liquid layout, which resizescontinually as you move the browser window’s sides around; instead, once a “trigger” point isreached the layout changes and affects the content You can see a good example of this tech-nique on Simon Collison’s web site CollyLogic (www.collylogic.com/), as shown in Figure 7-13

Figure 7-13. Simon Collison’s adaptable page layout on CollyLogic.com

On his site, Simon uses a combination of

• CSS (for the default styling options)

• JavaScript (to check for window resize events)

• DOM scripting (JavaScript that dynamically changes CSS display property values of theaffected elements)

Trang 12

Note It is possible to use floated elements to achieve a similar effect If the screen is big enough, theextra column floats back up into view, but if not, the column wraps This is a difficult effect to pull off con-vincingly without it appearing to be a bug, though!

We won’t cover this technique in detail, but Simon explains how it’s done here:

www.collylogic.com/?/comments/redesign-notes-1-width-based-layout/

Two Columns or Three?

So far we’ve seen a simple two-column design at work using various layout methods What if

we want to add in another column or two? In theory it’s just a matter of doing your sums rectly and making sure the figures don’t add up to more than 100 percent But as you add morecolumns to your design you may well run into issues regarding the source order (in other words,the order in which the different sections appear in the HTML source) and the display of thosecolumns Let’s see how adding columns works in an example page

cor-Say we want to add to the content area a new column for related links To do this, we’llplace the column inside the content’s outer container (content-wrapper); then we’ll use a float

to push the main content over to one side of that content-wrapper The related links will befloated on the other side Here’s the CSS with relevant parts highlighted in bold:

body {margin:10px 40px;

background:#dade75;

border:1px solid silver;

}

#header {background: #272727 url(header-bg.gif) repeat-x bottom left;

padding:10px 15px 10px 13px;

}

#content-wrapper {float:right;

background:#fff url(nav-to-content-trans.gif) repeat-y left;

Trang 13

#navigation {width:25%;

}

#footer {clear:both;

}

Note We’re applying our third column to the liquid layout that we discussed earlier Also notice that we’veadded just a smidgen of style to the links in the right column to remove some of the default padding in thelist items

The body of the page has also changed to accommodate the new links in the added column:

<li><a href="/prague/">Prague diary</a></li>

<li><a href="/sydney/">Sydney diary</a></li>

<li><a href="/italy/">Italy diary</a></li>

</ul>

</div>

</div>

Trang 14

<div id="navigation">

<ul>

<li><a href="day1.html">Day 1 (arrival)</a></li>

<li><a href="day2.html">Day 2 (kutna Hora)</a></li>

<li><a href="day3.html">Day 3 (Prague Castle)</a></li>

<li><a href="day4.html">Day 4 (up the towers, Karlstejn Castle)</a></li>

<li><a href="day5.html">Day 5 (Metro tour)</a></li>

You can see the result in Figure 7-14

Figure 7-14. We added the third column to the right of our page.

Changing Layouts at the Flick of a Switch

People often mention the need for multiple-page templates when dealing with content agement systems (CMSs) The pages typically have common themes but can differ significantly

man-in layout, such as the followman-ing:

• Pages with navigation on the left

• A page with no left navigation at all

• A three-column layout

• A page with only a header and one large image taking up the entire content area(a splash page)

Trang 15

It is a mistake to assume that each page needs to be built differently Using CSS, you cancreate a page structure that contains all the necessary hooks Think of placeholders in yourCMS or editable areas in a template on something like Dreamweaver, but use CSS to display orhide sections depending on what type of page you are in You specify the page type by using

an id or class attribute in the body element, which, through use of contextual selectors in theCSS, affects the rendering of elements further down in the document tree

Let’s look at another example page A corporate design, this page needs

• A header, for branding and search

• A breadcrumb trail

• Left navigation

• Content

• A third column for related information

• A footer that contains copyright information, back-to-top links, and so forthThis will be the default layout Let’s take a look at how that page could be built before westart switching the layout Here’s the complete page—CSS first:

body {margin:10px 40px;

color:#fff;

padding:10px;

}h1 {padding:0;

margin:0;

}

#breadcrumb {background: #009F9F;

color:#fff;

padding:5px 10px;

}

Trang 16

#breadcrumb a {color:#fff;

}

#content-wrapper {padding-left:9em;

padding-right:11em;

}

#navigation {position:absolute;

top:6.8em;

left:0;

}

#related {position:absolute;

padding-left:15px;

}

#related h2 {font-size:large;

}

#footer {padding:5px 0 5px 160px;

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"➥

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>Default document layout</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

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

</head>

Trang 17

<body id="cols3">

<div id="wrapper">

<div id="header"><h1>Fictional TravelCo &trade;</h1></div>

<div id="breadcrumb">

You are here: <a href="/travel/">Travel</a> &gt;

<a href="/travel/destinations/">Destinations</a> &gt; Europe

<li><a href="/linkdest1/">Nav link 1</a></li>

<li><a href="/linkdest2/">Nav link 2</a></li>

<li><a href="/linkdest3/">Nav link 3</a></li>

<li><a href="/linkdest4/">Nav link 4</a></li>

<li><a href="/linkdest5/">Nav link 5</a></li>

<li><a href="/related/">Related link</a></li>

<li><a href="/related/">Another link</a></li>

<li><a href="/related/">And another</a></li>

to calculate widths in CSS as 100 percent minus 200 pixels, for example) By using absolute positioning onthe left and right navigation elements and setting padding on the body content to match their widths, we canachieve a liquid layout regardless of the HTML source order

Trang 18

This layout is a hybrid of techniques:

• The overall page container is liquid, so text reflows as you resize the window

• The left and right columns (the main navigation and the related-links sections, tively) are positioned absolutely using ems This gets around the source order problemthat can occur with floated layouts; it’s as if we’ve placed the columns over the top ofthe main content, and that content has been pushed in using padding-left andpadding-rightproperties so that the text does not show underneath those two columns

respec-Figure 7-15 shows the net result

Figure 7-15. A simple but typical three-column layout

The main content is significantly larger (in terms of quantity) than the content in the sidecolumns, but the page layout holds together well, even when the window width is stretchedwide As we explained earlier, when you position an element absolutely, you remove it fromthe document flow and the outer containing element can collapse in underneath if no other

content is there to pad it out If there were more content in the absolutely positioned block,

the situation in Figure 7-16 could occur

Trang 19

Figure 7-16. Content pops out of the outer container (absolute positioning).

Later in this chapter we’ll refer you to another layout that gets around this problem Fornow, though, we wanted you to at least be aware of this potential hiccup in the layout, as youmay well come across it yourself and wonder about the cause

In the body element for the source code is an id:

<body id="cols3">

In the CSS, there’s currently nothing making use of that, so we’ll make some changes:

body#cols3 #content-wrapper {padding-left:9em;

padding-right:11em;

}body#cols3 #navigation {position:absolute;

top:6.8em;

left:0;

}body#cols3 #related {position:absolute;

top:6.8em;

right:10px;

}Now the CSS is telling the browser to lay out the two divs at the sides and add padding to

the main content only if they are contained in a document with a body id of cols3 If another

page calls that style sheet but has a different id in the body (or no id at all), it will ignore those stylesand simply present the markup in the order it appears in the source, as shown in Figure 7-17

Trang 20

Figure 7-17. This page has ignored the contextual styles applied to the three content areas.

So, make sure that you have the correct id in the <body> tag (cols3) and the browser willknow which piece of the CSS it should use to render the web page

Note We’ve used cols3as the idrather than 3cols—which would be a more appropriate name—

because an idcannot start with a number, according to the XHTML recommendations defined by the W3C(www.w3.org/TR/html4/types.html#h-6.2)

Switching the Design to a Splash Page

Let’s consider another variant of this design: a splash page that doesn’t require any left or rightnavigation (but the header and footer should remain) The first thing we need to do is changethe id value in the body element:

padding-right:1em;

}

Trang 21

body#splash #navigation {display:none;

}body#splash #related {display:none;

}body#splash #footer {padding:5px 0 5px 1.5em;

}The end result (with a fancy image in the content area instead of paragraphs of text) looks likeFigure 7-18

Figure 7-18. A splash page, switched using CSS

We’ve hidden the parts we don’t want to see and moved other parts of the page to fillthose spaces vacated But hang on a minute, what’s happened to the navigation and related-links lists? All we’ve done is hide them using the CSS display property; it may well be thatunless you’ve done a bit of pruning, unneeded content will exist in that markup Ideally, whatyou should have is something like this:

<body id="splash">

<div id="wrapper">

<div id="header"><h1>Fictional TravelCo &trade;</h1></div>

<div id="breadcrumb">

You are here: <a href="/travel/">Travel</a> &gt;

<a href="/travel/destinations/">Destinations</a> &gt; Europe

</div>

Trang 22

<div id="content-wrapper">

<div id="content-inner">

<h2>Prague - Charles Bridge</h2>

<p><img src="charles-bridge.jpg" alt="Charles Bridge at night" /></p>

Switching to a Section Entry Page

Let’s tweak the design once more to demonstrate the switching technique further Now we’regoing to do the following:

• Get rid of the related-links content

• Change the main content so that it takes up 50 percent of the design on the left-handside

• Move the navigation over to the right and increase the font size on those links tially

substan-We’re also going to change the content that appears in the relevant sections to reflect thetype of content we might expect to see in that layout Remember, though, that the overall pagestructure—the divs that hold everything together—will not change at all We’ll use this pagelayout as an entry page for a specific section of our site, so we’ll give it an id of entry:

<body id="entry">

Trang 23

And here are the additions to the CSS file:

/* Entry page styles */

body#entry #content-wrapper {padding-left:1em;

padding-right:50%;

}body#entry #navigation {font-size:x-large;

position:absolute;

top:4em;

right:20px;

}body#entry #related {display:none;

}body#entry #footer {padding:5px 0 5px 1.5em;

}Put it all together, and you get the page shown in Figure 7-19

Figure 7-19. An entry page to a site section

We hope you are beginning to see the power of using this technique You need only createthe hooks for areas of a web page that you may or may not need to populate with content anduse CSS to decide what gets shown Wave goodbye to CMS solutions that require differentpage templates for what may be fairly trivial cosmetic tweaks and let CSS take the strain

Trang 24

Faux Columns: Using Background Images

to Suggest Columns

When we discussed the three-column layout earlier, we fibbed a bit by calling them columns

Why? Because if you look at the layout, there’s a “perceived” column—that is, whitespace in

the navigation and related links areas suggests a column but it’s just a block of content floating

against a white background The moment we try to put a background color on that column orapply a border to it, everything goes wrong, as the unsightly foreground and background com-bination in Figure 7-20 shows:

#related {position:absolute;

Figure 7-20. The right column is not really a column at all.

If you are using floats or absolutely positioned elements in a layout like this, the contentwill not stretch to fill the available height of the containing element—unless you employJavaScript to do some clever calculations and resizing This means you cannot apply back-ground color that fills the entire height—or can you?

Faux Columns to the Rescue

Faux (or fake) columns are the solution (We snuck in an example of using faux columns

ear-lier when we discussed a fixed-width layout with a fixed height applied to the outer container.)Essentially, this approach involves using a background image, which is tiled along the y-axis

However, this image is applied not to the element that’s being floated or positioned but to an

element that sits behind that (one or more steps up the document tree) By doing this, you

Trang 25

avoid the worry of having to know the height of the element in the foreground This concept istricky to explain with words alone, so let’s look at an example.

First, we need the background image We’ll use one that has solid color and with whatappears to be a slightly darker border on the left side We created the image (Figure 7-21) sothat it matches exactly the fixed width of the related-links list that will sit over the top of it

Figure 7-21. The background image (which will be tiled)

In the CSS, we pick an appropriate element to attach it to An easy one is the outermostwrapper div; everything else sits inside this container and will appear to sit over the top of thisbackground image The image will be

• Aligned to the right of the container element

• Repeated along the y-axisHere’s the shorthand CSS that achieves this:

Figure 7-22. The background image appears underneath the absolutely positioned related-links section.

Hurray! It appears to have done the job, but once again, there’s a problem that you need

to be aware of

Ngày đăng: 14/12/2013, 17:15

TỪ KHÓA LIÊN QUAN