Tài liệu O_Reilly - CSS_ The Missing Manual 2nd Edition (2009)02 pptx

10 532 0
  • Loading ...
1/10 trang

Thông tin tài liệu

Ngày đăng: 27/01/2014, 09:20

Chapter 1: Rethinking HTML for CSS 21Writing HTML forCSSFigure 1-2:Old School, New School. Before CSS,designers had to resort to the <font>tag and other extra HTML to achievecertain visual effects (top). You canachieve the same look (and often abetter one) with a lot less HTML code(bottom). In addition, using CSS forformatting frees you up to write HTMLthat follows the logical structure of thepage’s content.GEM IN THE ROUGHSimple HTML Is Search Engine FriendlyOnce you take the mental leap of picturing HTML as theway to structure a document’s content, and CSS as the toolfor making that content look good, you’ll discover addi-tional benefits to writing lean, mean HTML. For one thing,you may boost your search-engine ranking as determinedby sites like Google, Yahoo, and MSN. That’s because whensearch engines crawl the Web, indexing the content onwebsites, they must go through all the HTML on a page todiscover the actual content. The old HTML way of usingspecial tags (like <font>) and lots of tables to design a pagegets in the way of a search engine’s job. In fact, some searchengines stop reading a page’s HTML after a certain numberof characters. When you use a lot of HTML just for design,the search engine may miss important content on the pageor even fail to rank it at all.By contrast, simple, structured HTML is easy for a searchengine to read and index. Using an <h1> tag to indicate themost important topic of the page (as opposed to just mak-ing the text big and bold) is smart strategy: Search enginesgive greater weight to the contents inside that tag whileindexing the page.To see Google’s suggestions for building search-friendlywebsites, visit www.google.com/webmasters/guidelines.html.For tips on writing HTML that can help your search-enginerankings visit www.digital-web.com/articles/seo_and_your_web_site/.<p><strong><font color="#0066FF" size="5" face="Verdana, Arial, Helvetica, sans-serif">Urban Agrarian Lifestyle</font></strong> <br /> <font color="#FF3300" size="4" face="Georgia, Times New Roman, Times, serif"><em><strong>A Revolution in Indoor Agriculture<br /></strong></em></font> Lorem ipsum dolor sit amet </p><h1>The Urban Agrarian Lifestyle</h1><h2>A Revolution in Indoor Agriculture</h2><p>Lorem ipsum dolor sit amet </p>Download at Boykma.Com22 CSS: The Missing ManualWriting HTML forCSSThe <div> tag and the <span> tag are like empty vessels that you fill with content. Adiv is a block, meaning it has a line break before it and after it, while a span appearsinline, as part of a paragraph. Otherwise, divs and spans have no inherent visualproperties, so you can use CSS to make them look any way you want. The <div> (fordivision) tag indicates any discrete block of content, much like a paragraph or a head-line. But more often it’s used to group any number of other elements, so you caninsert a headline, a bunch of paragraphs, and a bulleted list inside a single <div>block. The <div> tag is a great way to subdivide a page into logical areas, like a ban-ner, footer, sidebar, and so on. Using CSS, you can later position each area to createsophisticated page layouts (a topic that’s covered in Part 3 of this book).The <span> tag is used for inline elements; that is, words or phrases that appearinside of a larger paragraph or heading. Treat it just like other inline HTML tagssuch as the <a> tag (for adding a link to some text in a paragraph) or the <strong>tag (for emphasizing a word in a paragraph). For example, you could use a <span>tag to indicate the name of a company, and then use CSS to highlight the nameusing a different font, color, and so on. Here’s an example of those tags in action,complete with a sneak peek of a couple of attributes—id and class—frequentlyused to attach styles to parts of a page.<div id="footer"><p>Copyright 2006, <span class="bizName">CosmoFarmer.com</span></p><p>Call customer service at 555-555-5501 for more information</p></div>This brief introduction isn’t the last you’ll see of these tags. They’re used fre-quently in CSS-heavy web pages, and in this book you’ll learn how to use them incombination with CSS to gain creative control over your web pages (see the box onpage 54).HTML to ForgetCSS lets you write simpler HTML for one big reason: You can stop using a bunchof tags and attributes that only make a page better looking. The <font> tag is themost glaring example. Its sole purpose is to add a color, size and font to text. Itdoesn’t do anything to make the structure of the page more understandable.Here’s a list of tags and attributes you can easily replace with CSS:• Ditch <font> for controlling the display of text. CSS does a much better jobwith text. (See Chapter 6 for text-formatting techniques.)• Stop using <b> and <i> to make text bold and italic. CSS can make any tagbold or italic, so you don’t need these formatting-specific tags. However, if youwant to really emphasize a word or phrase, then use the <strong> tag (browsersdisplay <strong> text as bold anyway). For slightly less emphasis, use the <em>tag (browsers italicize content inside this tag).Download at Boykma.ComChapter 1: Rethinking HTML for CSS 23Writing HTML forCSSNote: To italicize a publication’s title, the <cite> tag kills two birds with one stone. It puts the title in italicsand tags it as a cited work for search engines’ benefit. This one’s a keeper.• Skip the <table> tag for page layout. Use it only to display tabular information likespreadsheets, schedules, and charts. As you’ll see in Part 3 of this book, you can doall your layout with CSS for much less time and code than the table-tag tango.• Eliminate the awkward <body> tag attributes that enhance only the presenta-tion of the content: background, bgcolor, text, link, alink, and vlink set colorsand images for the page, text, and links. CSS gets the job done better (seeChapter 7 and Chapter 8 for CSS equivalents of these attributes). Also trash thebrowser-specific attributes used to set margins for a page: leftmargin, topmar-gin, marginwidth, marginheight. CSS handles page margins easily (seeChapter 7).• Don’t abuse the <br> tag. If you grew up using the <br> tag (<br /> inXHTML) to insert a line break without creating a new paragraph, then you’re infor a treat. (Browsers automatically—and sometimes infuriatingly—insert a bitof space between paragraphs, including between headers and <p> tags. In thepast, designers used elaborate workarounds to avoid paragraph spacing theydidn’t want, like replacing a single <p> tag with a bunch of line breaks andusing a <font> tag to make the first line of the paragraph look like a headline.)Using CSS’s margin controls you can easily set the amount of space you want tosee between paragraphs, headers, and other block-level elements.Note: In the next chapter, you’ll learn about a technique called a “CSS Reset” which eliminates the gapsbrowsers normally insert between paragraphs and other tags (see page 102).As a general rule, adding attributes to tags that set colors, borders, backgroundimages, or alignment—including attributes that let you format a table’s colors,backgrounds, and borders—is pure old-school HTML. So is using alignment prop-erties to position images and center text in paragraphs and table cells. Instead, lookto CSS to control text placement (see page 130), borders (page 160), backgrounds(page 164), and image alignment (page 187).Tips to Guide Your WayIt’s always good to have a map for getting the lay of the land. If you’re still not surehow to use HTML to create well-structured web pages, then here are a few tips toget you started:• Use only one <h1> tag per page, and use it to identify the main topic of thepage. Think of it as a chapter title: You only put one title per chapter. Using<h1> correctly has the added benefit of helping the page get properly indexedby search engines (see the box on page 21).Download at Boykma.Com24 CSS: The Missing ManualWriting HTML forCSSUP TO SPEEDValidate Your Web PagesHTML follows certain rules: For example, the <html> tagwraps around the other tags on a page, and the <title> tagneeds to appear within the <head> tag. XHTML provides aneven more strict set of rules to follow. It’s easy to forgetthese rules or simply make a typo. Incorrect (or invalid,asthe geeks would say) HTML causes problems like makingyour page look different in different web browsers. Moreimportantly, you can’t create valid CSS with invalid HTML.Fortunately, there are tools for checking whether the HTMLin your web pages is correctly written.The easiest way to check—that is, validate—your pages is onthe W3C’s website at http://validator.w3.org/ (seeFigure 1-3). Get the Web Developer extension for Firefox(http://chrispederick.com/work/web-developer); it pro-vides a quick way to test a page in the W3C validator.The W3C, or World Wide Web Consortium, is the organiza-tion responsible for determining the standards for many ofthe technologies and languages of the Web, includingHTML, XHTML, and XML.If the W3C validator finds any errors in your page, it tellsyou what those errors are. If you use Firefox, you can down-load an extension that lets you validate a web page directlyin that browser, without having to visit the W3C site. It caneven attempt to fix any problems it encounters. You can getthe extension here: http://users.skynet.be/mgueury/mozilla/. A similar tool is available for the Safari browser aswell: www.zappatic.net/safaritidy/.Figure 1-3:The W3C HTML validator located athttp://validator.w3.org lets you quicklymake sure the HTML in a page is sound.You can point the validator to an alreadyexisting page on the Web, upload anHTML file from your computer, or justtype or paste the HTML of a web pageinto a form box and then click theCheck button.Download at Boykma.ComChapter 1: Rethinking HTML for CSS 25Writing HTML forCSS• Use headings to indicate the relative importance of text. Again, think outline.When two headings have equal importance in the topic of your page, use thesame level header on both. If one is less important or a subtopic of the other, thenuse the next level header. For example, follow an <h2> with an <h3> tag (seeFigure 1-4). In general, it’s good to use headings in order and try not to skip head-ing numbers. For example, don’t follow an <h2> tag with an <h5> tag.• Use the <p> tag for paragraphs of text.• Use unordered lists when you’ve got a list of several related items, such as navi-gation links, headlines, or a set of tips like these.• Use numbered lists to indicate steps in a process or define the order of a set ofitems. The tutorials in this book (see page 143) are a good example, as is a list ofrankings like “Top 10 websites popular with monks.”• To create a glossary of terms and their definitions or descriptions, use the <dl>(definition list) tag in conjunction with the <dt> (definition term) and <dd>(definition description) tags. (For an example of how to use this combo, visitwww.w3schools.com/tags/tryit.asp?filename=tryhtml_list_definition.)• If you want to include a quotation like a snippet of text from another web-site, a movie review, or just some wise saying of your grandfather’s, try the<blockquote> tag for long passages or the <q> tag for one-liners.• Take advantage of obscure tags like the <cite> tag for referencing a book title,newspaper article, or website, and the <address> tag to identify and supplycontact information for the author of a page (great for a copyright notice).Figure 1-4:Use the headline tags (<h1>, <h2>, and so on) as youwould if you were outlining a school report: Put them inorder of importance, beginning with an <h1> tag, whichshould shout “Listen up! This is what this whole pageis about.”<h1><h2><h3><h3>Download at Boykma.Com26 CSS: The Missing ManualThe Importance ofthe Doctype• As explained in full on page 22, steer clear of any tag or attribute aimed just atchanging the appearance of a text or image. CSS, as you’ll see, can do it all.• When there just isn’t an HTML tag that fits the bill, but you want to identify anelement on a page or a bunch of elements on a page so you can apply a distinc-tive look, use the <div> and <span> tags (see page 26). You’ll get more adviceon how to use these in later chapters (for example, page 312).• Don’t overuse <div> tags. Some web designers think all they need are <div>tags, ignoring tags that might be more appropriate. For example, to create anavigation bar, you could add a <div> tag to a page and fill it with a bunch oflinks. A better approach would be to use a bulleted list (<ul> tag). After all, anavigation bar is really just a list of links.• Remember to close tags. The opening <p> tag needs its partner in crime (theclosing </p> tag), as do all other tags, except the few self-closers like <br> and<img> (<br /> and <img /> in XHTML).• Validate your pages with the W3C validator (see Figure 1-3 and the box on page24). Poorly written or typo-ridden HTML causes many weird browser errors.The Importance of the DoctypeAs discussed in the box on page 24, HTML follows certain rules—these rules arecontained in a Document Type Definition file, otherwise known as a DTD. A DTDis an XML document that explains what tags, attributes, and values are valid for aparticular type of HTML. And for each version of HTML, there’s a correspondingDTD. By now you may be asking, “But what’s all this got to do with CSS?”Everything—if you want your web pages to appear correctly and consistently in webbrowsers. You tell a web browser which version of HTML or XHTML you’re usingby including what’s called a doctype declaration at the beginning of a web page. Thisdoctype declaration is the first line in the HTML file, and not only defines what ver-sion of HTML you’re using (such as HTML 4.01 Transitional) but also points to theappropriate DTD file on the Web. When you mistype the doctype declaration, youcan throw most browsers into an altered state called quirks mode.Quirks mode is browser manufacturers’ attempt to make their software behave likebrowsers did circa 1999 (in the Netscape 4 and Internet Explorer 5 days). If a mod-ern browser encounters a page that’s missing the correct doctype, then it thinks“Gee, this page must have been written a long time ago, in an HTML editor far, faraway. I’ll pretend I’m a really old browser and display the page just as one of thosebuggy old browsers would display it.” That’s why, without a correct doctype, yourlovingly CSS-styled web pages may not look as they should, according to currentstandards. If you unwittingly view your web page in quirks mode when checking itin a browser, you may end up trying to fix display problems that are related to anincorrect doctype and not the incorrect use of HTML or CSS.Download at Boykma.ComChapter 1: Rethinking HTML for CSS 27The Importance ofthe DoctypeNote: For more (read: technical) information on quirks mode, visit www.quirksmode.org/css/quirksmode.html and http://hsivonen.iki.fi/doctype/.Fortunately, it’s easy to get the doctype correct. All you need to know is what ver-sion of HTML you’re using. In all likelihood, you’re already creating web pagesusing HTML 4. You may even use XHTML for your websites (see page 5).The most popular versions of HTML and XHTML these days are HTML 4.01Transitional and XHTML 1.0 Transitional. These types of HTML still let you usepresentational tags like the <font> tag, thereby providing a transition from olderHTML to the newer, stricter types of HTML and XHTML. Although it’s best notto use these tags at all, they still work in the Transitional versions, so you can phaseout these older tags at your own pace. In the strict versions of HTML and XHTML,some older tags don’t work at all.Note: In general, the strict versions of both HTML and XHTML disallow tags and attributes aimed at mak-ing a page look good, like the <font> tag and a paragraph’s center attribute. They also disallow a numberof once-popular properties like a link’s target property, which lets you make a link open in a new window.If you’re using HTML 4.01 Transitional, type the following doctype declaration atthe very beginning of every page you create:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">The doctype declaration for XHTML 1.0 Transitional is similar, but it points to adifferent DTD. It’s also necessary to add a little code to the opening <html> tagthat’s used to identify the file’s XML type—in this case, it’s XHTML—like this:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">Note: If you’re using frames for your web pages, then you need to use a doctype intended for framesets.See the W3C site for a list of proper doctypes: www.w3.org/QA/2002/04/valid-dtd-list.html.If this entire discussion is making your head ache and your eyes slowly shut, justmake sure you use the proper doctype listed above, and always make it the first lineof your HTML file (before even the opening <html> tag). Also it’s easy to make atypo in this long-winded bit of code, so always make sure you validate the page (seethe box on page 36) to make sure your doctype is correct. In fact, it’s a good idea tohave a blank HTML page with the proper doctype somewhere on your computer, soyou can make a copy of it whenever you need to create a new web page. In the tuto-rial files available from www.sawmac.com/css2e, you’ll find four basic HTML files—one for each of the four main doctypes in use on the Web today.Download at Boykma.Com28 CSS: The Missing ManualGetting the Mostout of InternetExplorer 8Note: Most visual web page tools like Dreamweaver and Expression Web automatically add a doctypedeclaration whenever you create a new web page, and many HTML-savvy text editors have shortcuts foradding doctypes.Getting the Most out of Internet Explorer 8Thanks to Microsoft’s auto-update feature, the new Internet Explorer 8 has gaineda healthy share of the browser market. Fortunately for web designers, IE 8 is themost standards-compliant version of the browser yet. It fixes the bugs that haveplagued IE 6 and even IE 7, and works almost perfectly with version 2.1 of CSS.That means your carefully crafted web designs should look nearly the same in IE 8,Firefox, Safari, and Opera with little or no tinkering. As you’ll read later in thisbook (for example, pages 184 and 223), you can’t say the same about IE 6 or IE 7,which require some browser-specific code to make many designs look right.However, IE 8 is sort of like a chameleon: It can take on the appearance of a differ-ent version. If you’re not careful, it may not display your web pages the way youwant it to. For example, and most importantly, you must include a proper doc-type. As mentioned in the previous section, without a doctype, browsers switchinto quirks mode. Well, when IE 8 goes into quirks mode, it tries to replicate thelook of IE 5 (!?).But wait—there’s more! IE 8 can also pretend to be IE 7. When someone viewingyour site in IE 8 clicks a “compatibility view” button, IE 8 goes into IE 7 mode, dis-playing pages without IE 8’s full CSS 2.1 goodness. The same thing happens ifMicrosoft puts your website onto its Compatibility View List—a list of sites thatMicrosoft has determined look better in IE 7 than in IE 8. If you’re designing a siteusing the guidelines in this book, you won’t want IE 8 to act like IE 7…ever.Fortunately, there’s a way to tell IE 8 to stop all this nonsense and just be IE 8.Adding a single META tag to a web page instructs IE 8 to ignore CompatibilityView and the Compatibility View List and always display the page using its moststandards-compliant mode:<meta http-equiv="X-UA-Compatible" content="IE=edge" />Put this instruction in the page’s <head> section (below the <title> tag is a goodplace). This tag will work for future versions of IE, too: The “IE=edge” part of thetag will instruct versions of Internet Explorer that are released after IE 8 to also dis-play web pages in their standard mode. Unfortunately, you must do this on everypage of your site.Now that your HTML ship is steering in the right direction, it’s time to jump intothe fun stuff (and the reason you bought this book): Cascading Style Sheets.Download at Boykma.ComChapter 1: Rethinking HTML for CSS 29Getting the Mostout of InternetExplorer 8UP TO SPEEDCross Browser TestingThere are a lot of web browsers out there. If you use Win-dows, you automatically get Internet Explorer and caninstall additional browsers like Firefox, Safari, Opera, orGoogle’s Chrome. On a Mac, you can stick with the already-installed Safari browser, or run Firefox 3 or Chrome 1.While the very latest browsers are mostly comparable whendisplaying CSS-driven web pages, you can’t say the samefor IE 6, which is still in widespread use. Even IE 7 has itsshare of peculiarities.To really make sure your sites work for the largest audience,you need a way to test your designs in as wide a range ofbrowsers as possible. Here are a few techniques:Windows. Normally, Windows computers can only runone version of IE. In other words, you can’t test in IE 6, IE 7,and IE 8 on the same computer. Well, normally you can’t,but thanks to a nifty little program named IETester, you canactually see what a web page looks like in IE 5.5, IE 6, IE 7,and IE 8, all running side-by-side at the same time. Down-load this great program from www.my-debugbar.com/wiki/IETester/HomePage.You should also install the other major browsers on yourcomputer: Firefox, Safari, Opera, and Chrome. Fortunately,you don’t necessarily need a Mac for testing, since Apple’sbrowser—Safari—is also available for Windows.Mac. Testing is a bit trickier for Mac people. You have totest in Internet Explorer—it’s still the most used browser inthe world, and the display problems in IE 6 and IE 7 meanthat your painstakingly crafted design might look great foryou, but fall apart in IE. You have a few options: First, you canbuy (or borrow) a Windows machine; second, if you havean Intel Mac you can install Windows using Apple’s BootCamp software (www.apple.com/macosx/features/bootcamp.html); a third option is to install virtualizationsoftware like VMWare Fusion or Parallels Desktop on yourMac. This software lets you run a virtual Windows machine,side-by-side with the Mac OS. You can jump between Macand Windows to test in various browsers in both operatingsystems. It’s the most efficient testing technique for Macusers. Both Boot Camp and virtualization software requirea copy of the Windows OS.Everyone. Another option that works for both Windows andMacs and doesn’t require installing extra software is one ofthe many cross-browser testing services that let see whatyour pages look like in many different operating systems andbrowsers. Most of these are commercial services that costmoney. Litmus (http://litmusapp.com/) takes screenshots ofyour pages in a ton of different browsers; CrossBrowserTest-ing.com (www.crossbrowsertesting.com) lets you remotelyview another computer—in other words, you can actuallyinteract with a Windows machine, running Internet Explorer8, 7, and 6, plus Firefox and Safari. This scheme not only letsyou test the visual design, but also lets you interact with thepage and test how your JavaScript programming works inthat browser. One of the original services, Browsercam(www.browsercam.com), offers a wide range of servicesincluding both screenshots (like Litmus) and remote accessto real computers (like CrossBrowserTesting).Download at Boykma.ComDownload at Boykma.Com . HTML files—one for each of the four main doctypes in use on the Web today.Download at Boykma.Com28 CSS: The Missing Manual Getting the Mostout of InternetExplorer. for CSS 21Writing HTML for CSS Figure 1-2 :Old School, New School. Before CSS, designers had to resort to the <font>tag and other extra HTML to
- Xem thêm -

Xem thêm: Tài liệu O_Reilly - CSS_ The Missing Manual 2nd Edition (2009)02 pptx, Tài liệu O_Reilly - CSS_ The Missing Manual 2nd Edition (2009)02 pptx, Tài liệu O_Reilly - CSS_ The Missing Manual 2nd Edition (2009)02 pptx

Gợi ý tài liệu liên quan cho bạn