CSS isnât anything without HTML. HTML provides web pages with content and meaningful structure, and while it may not be pretty by itself, the web wouldnât exist without it. So to get the most out of your CSS training, you need to know how to write HTML to create a solid, well-built foundation. This chapter introduces you to the basics of CSS and shows you how to write better, more CSS-friendly HTML.
The good news is that when you use CSS throughout your site, HTML actually becomes easier to write. You donât need to try to turn HTML into the design maven it was never intended to be. Instead, CSS offers most of the graphic design touches youâll likely ever want, and HTML pages written to work with CSS are easier to create, since they require less code and less typing. Theyâll also download fasterâa welcome bonus your siteâs visitors will appreciate (see Figure 1-1).
HTML provides the foundation for every page you encounter on the Web. When you add CSS into the mix, HTML becomes simpler, because you donât need to use HTML tags (like the old <font>
tag) to control how a web page looks. That job is for CSS. But before jumping into CSS, hereâs a quick walk through HTMLâs past (and present).
When a bunch of scientists created the Web to share technical documentation, nobody called in the graphic designers. All the scientists needed HTML to do was structure information for easy comprehension. For example, the <h1>
tag indicates an important headline, while the <h2>
tag represents a lesser heading, usually a subheading of the <h1>
tag. Another favorite, the <ol>
(ordered list) tag, creates a numbered list for things like âTop 10 reasons not to play with jellyfish.â
Figure 1-1. CSS-driven web design makes writing HTML easier. The two designs pictured here look similar, but the top page is styled completely with CSS, while the bottom page uses only HTML. The size of the HTML file for the top page is only 4k, while the HTML-only page is nearly four times that size at 14k. The HTML-only approach requires a lot more code to achieve nearly the same visual effects: 213 lines of HTML code compared with 71 lines for the CSS version.
But as soon as people other than scientists started using HTML, they wanted their web pages to look good. So web designers started to use tags to control appearance rather than structure information. For example, you can use the <blockquote>
tag (intended for material thatâs quoted from another source) on any text that you want to indent a little bit. You can use heading tags to make any text bigger and bolderâregardless of whether it functions as a heading.
In an even more elaborate workaround, designers learned how to use the <table>
tag to create columns of text and accurately place pictures and text on a page. Unfortunately, since that tag was intended to display spreadsheet-like dataâresearch results, train schedules, and so onâdesigners had to get creative by using the <table>
tag in unusual ways, sometimes nesting a table within a table within a table to make their pages look good.
Meanwhile, browser makers introduced new tags and attributes for the specific purpose of making a page look better. The <font>
tag, for example, let you specify a font color, typeface, and one of seven different sizes. (If youâre keeping score at home, thatâs about 100 fewer sizes than you can get with, say, Microsoft Word.)
Finally, when designers couldnât get exactly what they wanted, they often resorted to using graphics. For example, theyâd create a large graphic to capture the exact font and layout for web page elements and then slice the Photoshop files into smaller files and piece them back together inside tables to recreate the original design.
While all of the preceding techniquesâusing tags in creative ways, taking advantage of design-specific tag attributes, and making extensive use of graphicsâprovide design control over your pages, they also add a lot of additional HTML code. More code makes your site more difficult to build and much slower for your visitors to download.
No matter what content your web page holdsâthe fishing season calendar, driving directions to the nearest IKEA, or pictures from your kidâs birthday partyâitâs the pageâs design that makes it look like either a professional enterprise or a part-timerâs hobby. Good design enhances the message of your site, helps visitors find what theyâre looking for, and determines how the rest of the world sees your website. Thatâs why web designers went through the contortions described in the previous section to force HTML to look good. By taking on those design duties, CSS lets HTML go back to doing what it does bestâstructuring content.
Using HTML to control the look of text and other web page elements is obsolete. Donât worry if HTMLâs <h1>
tag is too big for your taste or bulleted lists arenât spaced just right. You can take care of that later using CSS. Instead, think of HTML as a method of adding structure to the content you want up on the Web. Use HTML to organize your content and CSS to make that content look great.
If youâre new to web design, you may need some helpful hints to guide your forays into HTML (and to steer clear of well-intentioned, but out-of-date HTML techniques). Or if youâve been building web pages for a while, you may have picked up a few bad habits that youâre better off forgetting. The rest of this chapter introduces you to some HTML-writing habits that will make your mom proudâand help you get the most out of CSS.
HTML adds meaning to text by logically dividing it and identifying the role it plays on the page: For example, the <h1>
tag is the most important introduction to a pageâs content. Other headers let you divide the content into less important, but related sections. Just like this book, a web page needs a logical structure. Each chapter in this book has a title (think <h1>
) and several sections (think <h2>
), which in turn contain smaller subsections. Imagine how much harder it would be to read these pages if the words just ran together as one long paragraph.
Note
For a tutorial on HTML, visit www.w3schools.com/html/html_intro.asp. For a quick list of all available HTML tags, visit the detailed (but a bit technical) reference at the Mozilla Developer network: https://developer.mozilla.org/en-US/docs/Web/HTML/Element.
HTML provides many other tags besides headers for marking up content to identify its role. (After all, the M in HTML stands for markup.) Among the most popular are the <p>
tag for paragraphs of text and the <ul>
tag for creating bulleted (non-numbered) lists. Lesser-known tags can indicate very specific types of content, like <abbr>
for abbreviations and <code>
for computer code.
When writing HTML for CSS, use a tag that comes as close as possible to matching the role the content plays in the page, not the way it looks (see Figure 1-2). For example, a bunch of links in a navigation bar isnât really a headline, and it isnât a regular paragraph of text. Itâs most like a bulleted list of options, so the <ul>
tag is a good choice. If youâre saying, âBut items in a bulleted list are stacked vertically one on top of the other, and I want a horizontal navigation bar where each link sits next to the previous link,â donât worry. With CSS magic you can convert a vertical list of links into a stylish horizontal navigation bar, as youâll see in Chapter 9.
HTMLâs motley assortment of tags doesnât cover the wide range of content youâll likely have on a web page. Sure, <code>
is great for marking up computer program code, but most folks would find a <recipe>
tag handier. Too bad there isnât one. Fortunately, HTML provides several âstructuralâ tags that let you better identify and group content, and, in the process, provide âhandlesâ that let you attach CSS styles to different page elements. Two of those tagsâ<div>
and <span>
âhave been around nearly since the beginning of HTML. HTML5 introduced a much wider range of tags that let you group content that serves a particular function, like the <footer> tag, which you can use to group supplementary information like a copyright notice, contact information, or a list of resources.
Figure 1-2. Old school, new school. Before CSS, designers had to resort to the <font> tag and other extra HTML to achieve certain visual effects (top). You can achieve the same look (and often a better one) with a lot less HTML code (bottom). In addition, using CSS for formatting frees you up to write HTML that follows the logical structure of the pageâs content.
The <div>
and <span>
tags have been around for much of the life of the Web. Theyâve traditionally been used to organize and group content that doesnât quite lend itself to other HTML tags. Think of them as like empty vessels that you fill with content. A div is a block, meaning it has a line break before it and after it, while a span appears inline, as part of a paragraph. Otherwise, divs and spans have no inherent visual properties, so you can use CSS to make them look any way you want. The <div>
(for division) tag indicates any discrete block of content, much like a paragraph or a headline. But more often itâs used to group any number of other elements, so you can insert 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 banner, footer, sidebar, and so on. Using CSS, you can later position each area to create sophisticated page layouts (a topic thatâs covered in Part 3).
The <span>
tag is used for inline elements: words or phrases that appear inside a larger paragraph or heading. Treat it just like other inline HTML tags, such 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 name by using a different font, color, and so on. Hereâs an example of these tags in action, complete with a sneak peek of a couple of attributesâid
and class
âfrequently used to attach styles to parts of a page.
<div id="footer">
<p>Copyright 2015,<span class="bizName">
SuperCo.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 frequently in CSS-heavy web pages, and in this book youâll learn how to use them in combination with CSS to gain creative control over your web pages.
The <div>
tag is rather genericâitâs simply a block-level element used to divide a page into sections. One of the goals of HTML5 is to provide other, more semantic tags for web designers to choose from. Making your HTML more semantic simply means using tags that accurately describe the content they contain. As mentioned earlier in this section, you should use the <h1>
(heading 1) tag when placing text that describes the primary content of a page. Likewise, the <code>
tag tells you clearly what kind of information is placed insideâprogramming code.
HTML5 includes many different tags whose names reflect the type of content they contain, and can be used in place of the <div>
tag. The <article>
tag, for example, is used to mark off a section of a page that contains a complete, independent composition, like a blog post, an online magazine article, or simply the pageâs main body of text. Likewise, the <header>
tag indicates a header or banner: the top part of a page, usually containing a logo, sitewide navigation, page title and tagline, and so on.
Note
To learn more about the new HTML tags, visit HTML5 Doctor (http://html5doctor.com) and www.w3schools.com/html/html5_intro.asp or grab a copy of the HTML5 Pocket Reference (OâReilly).
Many HTML5 tags are intended to expand upon the generic <div>
tag. Here are a few other HTML5 tags frequently used to structure the content on a page:
The
<section>
tag contains a grouping of related content, such as the chapter of a book. For example, you could divide the content of a home page into three sections: one for an introduction to the site, one for contact information, and another for latest news.The
<aside>
tag holds content that is related to content around it. A sidebar in a print magazine is an example of the type of content that would go into an<aside>
.The
<footer>
tag contains information youâd usually place in a pageâs footer, like a copyright notice, legal information, some site navigation links, and so on. Youâre not limited to just a single<footer>
per page, though; you can put a footer inside an<article>
, for example, to hold related information like footnotes, references, or citations.The
<nav>
element is used to contain primary navigation links.The
<figure>
tag is used for an illustrative image. You can place an<img>
tag inside it, as well as another new HTML5 tagâthe<figcaption>
tag, which is used to display a caption explaining the photo or illustration within the<figure>
.
Tip
Understanding which HTML5 tag to useâshould your text be an <article>
or a <section>
?âcan be tricky. For a handy flowchart that makes sense of HTML5âs new sectioning elements, download the PDF from the HTML5doctor.com at http://html5doctor.com/downloads/h5d-sectioning-flowchart.pdf.
There are other HTML5 elements, and many of them simply provide a more descriptive alternative to the <div>
tag. This book uses both the <div>
tag and the new HTML5 tags to help organize web-page content. The downside of HTML5 is that Internet Explorer 8 and earlier donât recognize the new tags without a little bit of help (see the box on Getting IE8 to Understand HTML5).
In addition to letting you feel like youâre keeping up with the latest web design trends, using HTML5 tags provides you with clues about a pageâs content, and may boost the siteâs search engine ranking. For example, using the <article>
tag to hold the main story on a web page can highlight whatâs inside that tag, and is more descriptive (that is, semantic) than a plain old <div>
. Even so, many web designers still use <div>
tags even in places where an HTML5 tag makes sense, so thereâs no harm in continuing to use the <div>
tag and avoiding the HTML5 sectioning elements if you like.
In addition, even with the HTML5 tags, sometimes you still need use <div>
tags simply to group other HTML tags. Youâd do this to provide a way to move that group to another spot on a page, to give the group a consistent background color, or to draw an outline and add a drop shadow.
While youâll use the <h1>
tag to identify the main topic of the page and the <p>
tag to add a paragraph of text, youâll eventually want to organize a pageâs content into a pleasing layout. As you learn how to use CSS to lay out a page in Part 3, it doesnât hurt to keep your design in mind while you write the pageâs HTML.
You can think of web page layout as the artful arrangement of boxes (see Figure 1-3 for an example). After all, a two-column design consisting of two vertical columns of text is really just two rectangular boxes sitting side by side. A header consisting of a logo, tagline, search box, and site navigation is really just a wide rectangular box sitting across the top of the browser window. In other words, if you imagine the groupings and layout of content on a page, youâd see boxes sitting on top of, next to, and below one another.
Figure 1-3. This basic two-column layout includes a banner (top), a column of main content (middle, left), a sidebar (middle, right), and a footer (bottom). These are the main structural boxes making up this pageâs layout.
In your HTML, you create these boxes, or structural units, using the <div>
tag, or one of HTML5âs structural tags like <footer>
, <header>
, <article>
, and <aside>
. Simply wrap the HTML tags that make up the banner area, for example, in one div, a columnâs worth of HTML in another, and so on. If youâre HTML5 savvy, you might create the design pictured in Figure 1-3, with a <header>
tag for the top banner, an <article>
tag for the main text, an <aside>
or <section>
tag for the sidebar, and a <footer>
tag for the pageâs footer. In other words, if you plan to place a group of HTML tags together somewhere on a page, then youâll need to wrap those tags in a sectioning element like a <div>
, <article>
, <section>
, or <aside>
.
As youâll learn in Part 3, CSS provides powerful layout tools. You can literally place HTML anywhere in the browser window; recent developments like flexbox (Chapter 15) give you lots of freedom in how you structure your HTML. Still, itâs always a good idea to group related content into some kind of container element like a <div>
or an HTML5 structural tag.
Microsoft says it will discontinue support for Internet Explorer 8 by January 2016. At that point, Windows fans will have more incentive to upgrade IE or switch to another browser, like Chrome or Firefox. The biggest problem with IE8 is that it doesnât understand HTML5 tags, which means you canât directly format these tags with CSS. If youâre really worried about supporting Internet Explorer 8, either skip the HTML5 tags described on Additional Tags in HTML5 for structuring your HTML and stick to <div>
tags, or use the quick JavaScript solution described in the box on Getting IE8 to Understand HTML5.
CSS lets you write simpler HTML for one big reason: There are many old HTML tags that you should abandon (if youâre still using them). The <font>
tag is the most glaring example. Its sole purpose is to add a color, size and font to text. It doesnât do anything to make the pageâs structure 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 job with text. (See Chapter 6 for text-formatting techniques.)Donât use the
<b>
and<i>
tags to emphasize text. If you want text to really be emphasized, use the<strong>
tag, which browsers normally display as bold. For a slightly less emphatic point, use the<em>
tag, which browsers display as italic. You can use CSS to make any text on a page italicized, bolded, or both.While HTML 4 tried to phase the
<b>
and<i>
tags out, HTML5 has brought them back. In HTML5 the<b>
tag is meant to merely make text bold without adding any meaning to that text (that is, you just want the text to be bold looking but you donât want people to treat that text like youâre shouting it). Likewise, the<i>
tag is used for italicizing text, but not emphasizing its meaning.Note
To italicize a publicationâs title, the
<cite>
tag kills two birds with one stone. It puts the title in italics and tags it as a cited work for search enginesâ benefit. Of course, CSS lets you do anything you want with the tag, so if you want to reference a publication and not italicize it, you can still use the<cite>
tag.Skip the
<table>
tag for page layout. Use tables only to display information like spreadsheets, schedules, and charts. As youâll see in Part 3, you can do all your layout with CSS for much less time and code than the table-tag tango.Donât abuse the
<br>
tag. If you grew up using the<br>
tag to insert a line break without creating a new paragraph, then youâre in for a treat. (Browsers automaticallyâand sometimes infuriatinglyâinsert a bit of space between paragraphs, including between headers and<p>
tags. In the past, designers used elaborate workarounds to avoid paragraph spacing they didnât want, like replacing a single<p>
tag with a bunch of line breaks and using 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 to see between paragraphs, headers, and other block-level elements.
Note
In Chapter 5, youâll learn about a technique called a âCSS Reset,â which eliminates the gaps browsers normally insert between paragraphs and other tags (see Starting with a Clean Slate).
As a general rule, adding attributes to tags that set colors, borders, background images, or alignmentâincluding attributes that let you format a tableâs colors, backgrounds, and bordersâis pure old-school HTML. So is using alignment properties to position images and center text in paragraphs and table cells. Instead, look to CSS to control text placement (Aligning Text), borders (Adding Borders), backgrounds (Adding Background Images), and image alignment (Discovering CSS and the <img> Tag).
Figure 1-4. The W3C HTML validator located at http://validator.w3.org lets you quickly make sure the HTML in a page is sound. You can point the validator to an already existing page on the Web, upload an HTML file from your computer, or just paste the HTML of a web page into a form box and then click the Check button.
Itâs always good to have a map to get the lay of the land. If youâre still not sure how to use HTML to create well-structured web pages, then here are a few tips to get you started:
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 the same level header on both. If one is less important or a subtopic of the other, then use the next-level header. For example, follow an
<h2>
with an<h3>
tag (see Figure 1-5). In general, itâs good to use headings in order and try not to skip heading numbers. For example, donât follow an<h2>
tag with an<h5>
tag.Use unordered lists (
<ul>
) when youâve got a list of several related items, such as navigation links, headlines, or a set of tips like these.Use numbered lists (
<ol>
) to indicate steps in a process or define the order of a set of items. The tutorials in this book are a good example, as is a list of rankings 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, visit http://htmldog.com/guides/html/intermediate/definitionlists/.)If you want to include a quotation like a snippet of text from another website, a movie review, or just some wise saying of your grandfatherâs, try the
<blockquote>
tag for long passages or the<q>
tag to place a short quote within a longer paragraph, like this:<p>Mark Twain is said to have written <q>The coldest winter I ever spent was a summer in San Francisco</q>. Unfortunately, he never actually wrote that famous quote.</p>
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 supply contact information for the author of a page (great for a copyright notice).As explained in full on HTML: Past and Present, steer clear of any tag or attribute aimed solely at changing the appearance of a text or image. CSS, as youâll see, can do it all.
When there isnât an HTML tag that fits the bill, but you want to identify an element on a page or a bunch of elements on a page so you can apply a distinctive look, use the
<div>
and<span>
tags (see Understanding the <div> and <span> Tags). Youâll get more advice on how to use these in later chapters.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 a navigation bar, you could add a<div>
tag to a page and fill it with a bunch of links. A better approach would be to use a bulleted list (<ul>
tag), After all, a navigation bar is really just a list of links. As discussed on Additional Tags in HTML5, HTML5 provides several new tags that can take the place of the<div>
tag, like the<article>
,<section>
, and<footer>
tags. For a navigation bar, you could use the HTML5<nav>
tag.Remember to close tags. The opening
<p>
tag needs its partner in crime (the closing</p>
tag), as do all other tags, except the few self-closers like<br>
and<img>
.Validate your pages with the W3C validator (see Figure 1-4 and the box on Validate Your Web Pages). Poorly written or typo-ridden HTML causes many weird browser errors.
HTML follows certain rules. You tell a web browser which version of HTML youâre using (and which rules youâre following) by including whatâs called a doctype declaration at the beginning of a web page. This doctype declaration is the first line in the HTML file, and defines what version of HTML youâre using (such as HTML5 or HTML 4.01 Transitional).
If you mistype the doctype declaration or leave it out, you can throw most browsers into an altered state called quirks mode. Quirks mode is browser manufacturersâ attempt to make their software behave like browsers did circa 1999 (in the Netscape 4 and Internet Explorer 5 days). If a modern 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, far away. Iâll pretend Iâm a really old browser and display the page just as one of those buggy old browsers would display it.â Thatâs why, without a correct doctype, your lovingly CSS-styled web pages may not look as they should, according to current standards. If you unwittingly view your web page in quirks mode when checking it in a browser, you may end up trying to fix display problems that are related to an incorrect doctype and not the incorrect use of HTML or CSS.
Note
For more (read: technical) information on quirks mode, visit www.quirksmode.org/css/quirksmode.html and https://developer.mozilla.org/en-US/docs/Quirks_Mode_and_Standards_Mode.
Fortunately, itâs easy to get the doctype right. All you need to know is what version of HTML youâre using. Almost everyone is using HTML5 now, and the doctype is simply:
<!doctype html>
Put this at the top of your HTML file and youâre good to go. If youâre still using older versions of HTML or XHTML such as HTML 4.01 Transitional and XHTML 1.0 Transitional, then the doctype is a lot more convoluted.
If youâre using HTML 4.01 Transitional, for example, type the following doctype declaration at the 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. Itâs also necessary to add a little code to the opening <html> tag thatâ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">
If this entire discussion is making your head ache and your eyes slowly shut, keep your life simple by using the HTML5 doctype. Itâs short, easy to remember, works in all browsers, and what almost all new web pages use. You can use this doctype even if you donât touch any of the new HTML5 tags.
Now that you have a solid background on writing HTML for CSS, youâre ready for what this book is all about. CSS is the styling language used to format HTML-based web pages. While HTML provides the pageâs structure, CSS works hand in hand with the web browser to make HTML look good on screen.
For example, you might use HTML to turn a phrase into a top-level heading, indicating that it introduces the content on the rest of the page. Youâd use CSS to format that heading with, say, big and bold red type and position it 50 pixels from the left edge of the window. In CSS, that text formatting is a styleâa rule describing the appearance of a particular portion of a web page. A style sheet is a set of these styles.
You can create styles to work with any HTML tag. For example, you can create styles specifically to format the images on a page. For instance, a style can align an image along the pageâs right edge, surround the image with a colorful border, and place a 50-pixel margin between the image and the surrounding text.
The web browser applies the styles you create to text, images, headings, and other page elements. For example, you can create a style that applies to a single paragraph on your page to instantly change the textâs size, color, and font within that paragraph. You can create styles that apply to specific HTML tags, so, for example, a browser displays every first-level heading (<h1>
tag) in your site in the same way, no matter where those headings appear. You can even create styles that apply only to specific tags that youâve marked up in a special way in the HTML.
Creating styles is all about determining what you want to style (a single image, every image, every other item in a list, and so on) and how you want that selected element or elements to look. In fact, determining what you want to style is such a big topic, Chapters Chapter 3, Chapter 4, and Chapter 5 of this book are devoted to the subject. All of the different ways you can make page elements look is an even bigger topic, and is covered in Part 2.
Get CSS: The Missing Manual, 4th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.