CSS responsive Web design examples

css and html web design pdf and css presentation framework and css & html web design for beginners
JohenCorner Profile Pic
Published Date:02-08-2017
Your Website URL(Optional)
a CASCADING STYLE SHEETS ORIENTATION You’ve seen style sheets mentioned quite a bit already, and now we’ll finally put them to work and start giving our pages some much needed style. Casc ading Style Sheets (CSS) is the W3C standard for defining the pre- sentation of documents written in HTML, XHTML, and, in fact, any XML language. Presentation, again, refers to the way the document is displayed or delivered to the user, whether on a computer screen, a cell phone display, or read aloud by a screen reader. With style sheets handling the presentation, (X)HTML can get back to the business of defining document structure and meaning, as intended. CSS is a separate language with its own syntax. This chapter covers CSS ter- minology and fundamental concepts that will help you get your bearings for the upcoming chapters, where you’ll learn how to change text and font styles, add colors and backgrounds, and even do basic page layout using CSS. Will you be a style sheet expert by the end of Part III? Probably not. But you will have a solid foundation for further reading, and lots of practice. N ot e See the section, Moving Forward with CSS, at the end of this chapter for books and sites that will help you continue your education. The Benefits of CSS Not that you need further convincing that style sheets are the way to go, but here is a quick run-down of the benefits of using style sheets. • Better type and layout controls. Presentational (X)HTML never gets close to offering the kind of control over type, backgrounds, and layout that is possible with CSS. • Less work. You can change the appearance of an entire site by editing one style sheet. Making small tweaks and even entire site redesigns with style sheets is much easier than when presentation instructions are mixed in with the markup. 1a How Style Sheets Work • Potentially smaller documents and faster downloads. Old school prac- tices of using redundant font elements and nested tables make for bloated documents. Not only that, you can apply a single style sheet document to all the pages in a site for further byte savings. • More accessible sites. When all matters of presentation are handled by CSS, you can mark up your content meaningfully, making it more acces- sible for nonvisual or mobile devices. • Reliable browser support. Nearly every browser in current use supports all of CSS Level 1 and the majority of CSS Level 2. (See the sidebar, Meet the Standards, for what is meant by CSS “levels.”) Come to think of it, there really aren’t any disadvantages to using style sheets. There are some lingering hassles from browser inconsistencies, but they can M Meet eet the the S Standar tandards ds either be avoided or worked around if you know where to look for them. It’s T The he first first official official v version ersion of of CSS CSS (the (the by no means a reason to put off using CSS right away. CSS CSS L Le ev vel el 1 1 R Recommendation ecommendation, , a.k a.k.a .a CSS1 CSS1) ) was was officially officially r released eleased in in 1996, 1996, and and included included pr proper operties ties f for or adding adding The power of CSS f font, ont, color color, , and and spacing spacing instruc instructions tions t to o page page elements elements. . Unf Unfor ortunat tunately ely, , We’re not talking about minor visual tweaks here, like changing the color lack lack of of dependable dependable br bro owser wser suppor support t of headlines or adding text indents. When used to its full potential, CSS is pr pre ev vent ented ed the the widespr widespread ead adoption adoption a robust and powerful design tool. My eyes were opened by the variety and of of CSS CSS f for or se sev veral eral y years ears. . richness of the designs at CSS Zen Garden (www.csszengarden.com). Figure CSS CSS L Le ev vel el 2 2 ( (CSS2 CSS2) ) was was r released eleased 11-1 shows just a few of my favorites. All of these designs use the exact same in in 1998. 1998. IIt t most most notably notably added added pr proper operties ties f for or positioning positioning that that XHTML source document. Not only that, it doesn’t include a single img ele- allo allow wed ed CSS CSS t to o be be used used f for or page page ment (all of the images are used as backgrounds). But look how different each la lay yout. out. IIt t also also intr introduced oduced st styles yles f for or page looks—and how sophisticated—that’s all done with style sheets. other other media media t types ypes (such (such as as pr print, int, handheld handheld, , and and aural) aural) and and mor more e Granted, it takes a lot of practice to be able to create CSS layouts like those sophisticat sophisticated ed methods methods f for or selec selecting ting shown in Figure 11-1. Killer graphic design skills help too (unfortunately, you elements elements f for or st styling yling. . CSS CSS L Le ev vel el 2, 2, won’t get those in this book). I’m showing this to you up front because I want R Re evision vision 1 1 ( (CSS2.1 CSS2.1) ) mak makes es some some minor minor adjustments adjustments t to o CSS2 CSS2 and and is is you to be aware of the potential of CSS-based design, particularly because the a a w wor ork king ing draf draft t as as of of this this wr writing iting. . examples in this beginners’ book tend to be simple and straightforward. Take F For ortunat tunately ely, , most most cur curr rent ent br bro owsers wsers your time learning, but keep your eye on the prize. suppor support t the the major majorit ity y of of the the CSS1, CSS1, CSS2, CSS2, and and CSS2.1 CSS2.1 specifications specifications.. IIn n fac fact, t, some some br bro owsers wsers ar are e alr already eady suppor supporting ting f featur eatures es fr from om CSS CSS L Le ev vel el How Style Sheets Work 3 3 ( (CSS3 CSS3) ) that that is is still still in in de dev velopment. elopment. It’s as easy as 1-2-3 IIt t adds adds suppor support t f for or v ver ertical tical t tex ext, t, impr impro ov ved ed handling handling of of tables tables and and 1. Start with a document that has been marked up in HTML or XHTML. int inter ernational national languages languages, , bett better er int integ egration ration with with other other XML XML 2. Write style rules for how you’d like certain elements to look. t technolog echnologies ies, , and and other other little little per perks ks lik like e multiple multiple back backg gr round ound images images in in 3. Attach the style rules to the document. When the browser displays the a a single single element element and and a a lar larger ger list list of of document, it follows your rules for rendering elements (unless the user color color names names. . has applied some mandatory styles, but we’ll get to that later). K Keep eep up up t to o dat date e with with the the W3C W3C’’s s de dev velopment elopment of of CSS CSS at at w ww ww w.w3.or .w3.org/ g/ OK, so there’s a bit more to it than that, of course. Let’s give each of these steps St Style/CSS yle/CSS. . a little more consideration. 1 Part III: CSS for Presentationa How Style Sheets Work CSS Zen Dragen by Matthew Buchanan Faded Flowers By the Pier by Mani Sheriar by Peter OngKelmscott Shaolin Yokobue by Javier Cabrera Organica Creativa Kelmscott Contemporary Nouveau by Eduardo Cesario by Bronwen Hodgkinson by David Hellsing Figure 11-1. These pages from the CSS Zen Garden use the same XHTML source document, but the design is changed using exclusively CSS (used with permission of CSS Zen Garden and the individual designers). Chapter 11, Cascading Style Sheets Orientation 1a How Style Sheets Work 1. Marking up the document You know a lot about marking up content from the previ- exercise 11-1 ous chapters. For example, you know that it is important Your first style sheet to choose (X)HTML elements that accurately describe the meaning of the content. You’ve also heard me say that the In this exercise, we’ll add a few simple styles to a short markup creates the structure of the document, sometimes article. The XHTML document, twenties.html and its called the structural layer, upon which the presentation associated image, twenty_20s.jpg, are available at www. layer can be applied. learningwebdesign.com/materials/. First, open the document in a browser to see how it looks by default In this and the upcoming chapters, you’ll see that having (it should look something like Figure 11-2). You can also an understanding of your document’s structure and the open the document in a text editor and get ready to follow along when this exercise continues in the next relationships between elements is central to your work as section. a style sheet author. To get a feel for how simple it is to change the look of a document with style sheets, try your hand at Exercise 11-1. The good news is that I’ve whipped up a little XHTML document for you to play with. 2. Writing the rules A style sheet is made up of one or more style instructions (called rules) that describe how an element or group of ele- ments should be displayed. The first step in learning CSS is to get familiar with the parts of a rule. As you’ll see, they’re fairly intuitive to follow. Each rule selects an element and declares how it should look. The following example contains two rules. The first makes Figure 11-2. This what the article looks like without all the h1 elements in the document green; the second any style sheet instructions. Although we won’t be specifies that the paragraphs should be in a small, sans- making it beautiful, you will get a feel for how styles serif font. work. h1 color: green; p font-size: small; font-family: sans-serif; N ot e Sans-serif fonts do not have a little slab (a serif) at the ends of strokes and tend to look more sleek and modern. We’ll talk a lot more about fonts in Chapter 12, Formatting Text. In CSS terminology, the two main sections of a rule are the selector that iden- tifies the element or elements to be affected, and the declaration that provides the rendering instructions. The declaration, in turn, is made up of a property (such as color) and its value (green), separated by a colon and a space. One or more declarations are placed inside curly brackets, as shown in Figure 11-3. 1 0 Part III: CSS for Presentationa How Style Sheets Work declaration declaration block selector property: value; selector property1: value1; property2: value2; property3: value3; Figure 11-3. The parts of a style sheet rule. Selectors In the previous small style sheet example, the h1 and p elements are used as selectors. This most basic type of selector is called an element type selector. The properties defined for each will apply to every h1 and p element in the document, respectively. In upcoming chapters, I’ll introduce you to more sophisticated selectors that you can use to target elements, including ways to select groups of elements and elements that appear in a particular context. Mastering selectors—that is, choosing the best type of selector and using it strategically—is an important step in becoming a CSS Jedi Master. Declarations The declaration is made up of a property/value pair. There can be more than N N oott ee one declaration in a single rule; for example, the rule for p element above T Te echn chnically ically, , the the s sem emic icolo olon n is is n no ot t r re equi quir re ed d has both the font-size and font-family properties. Each declaration must a aft fte er r the the last last de decla clar ra at ti io on n i in n the the blo bloc ck, k, b bu ut t end with a semicolon to keep it separate from the following declaration (see i it t is is r re ec co omm mmende ended d tha that t yo you u g get et i int nto o the the note). If you omit the semicolon, the declaration and the one following it will hab habi it t of of al alw wa ay ys s end endi in ng g de decla clar ra at ti io ons ns w wi ith th a a s sem emic icolo olon n. . I It t w will ill m mak ake e a add ddi in ng g de decla clar ra a- - be ignored. The curly brackets and the declarations they contain are often t ti io ons ns t to o the the r rule ule la lat te er r tha that t m much uch e eas asi ie er r. . referred to as the declaration block (Figure 11-3). Because CSS ignores whitespace and line returns within the declaration block, authors typically write each declaration in the block on its own line, as shown in the following example. This makes it easier to find the properties applied to the selector and to tell when the style rule ends. p font-size: small; font-family: sans-serif; N N oott ee Note that nothing has really changed here—there is still one set of curly F Fo or r a a c co om mp plet lete e l list ist of of p pr ro ope pert rti ie es s i in n the the brackets, semicolons after each declaration, etc.. The only difference is the c cu ur rr re en nt t C CS SS S2 2. .1 1 s st ta an nd da ar rd ds s, , g go o s st tr ra ai ig gh ht t insertion of line returns and some character spaces for alignment. t to o the the W3C W3C R Re ec co omm mmenda endat ti io on n a at t www www. . w3 w3.o .org/TR/CSS2 rg/TR/CSS21 1/p /pr ro op pidx idx.html .html, , o or r c co on n- - The heart of style sheets lies in the collection of standard properties that sult sult a a c co om mp pr rehens ehensi iv ve e CSS CSS r ref efe er rence ence b bo ook ok can be applied to selected elements. The complete CSS specification defines such such as as CSS: CSS: The The Def Defi in ni it ti iv ve e Guide Guide b by y dozens of properties for everything from text indent to how table headers Eric Eric M Mey eye er r o or r W Web eb De Des si ign gn i in n a a N Nu utshell tshell should be read aloud. This book covers the most common and best sup- b by y J Jenn ennif ife er r R Robb obbi ins ns (tha (that’ t’s s m me) e), , b bo oth th p publ ublishe ished d b by y O O’’R Reilly eilly M Me ed di ia a. . ported properties (see note). Chapter 11, Cascading Style Sheets Orientation 1 1a How Style Sheets Work Values are dependent on the property. Some proper- ties take length measurements, some take color values, Providing Measurement Values others have a predefined list of keywords. When using When providing measurement values, the unit must a property, it is important to know which values it immediately follow the number , like this: accepts; however, in many cases, simple common sense margin: 2em; will serve you well. Adding a space before the unit will cause the property not to work. Before we move on, why not get a little practice writing INCORRECT: margin: 2 em; style rules yourself in the continuation of Exercise 11-1. It is acceptable to omit the unit of measurement for zero values: margin: 0; exercise 11-1 Your first style sheet (continued) Open twenties.html in a text editor. In the head of the  Add a 100 pixel left margin to the h2 headings as well. document you will find that I have set up a style element for  Add a red, 1-pixel border to the bottom of the h1 element you to type the rules into. The style element is used to embed using this declaration: a style sheet in the head of an (X)HTML document. border-bottom: 1px solid red; To begin, we’ll just add the small style sheet that we just looked  Move the image to the right margin and allow text to flow at in this section. Type the following rules into the document, around it with the float property. The shorthand margin just as you see them here. property shown in this rule adds zero pixels space on the style type="text/css" top and bottom of the image and 12 pixels space on the left h1 and right of the image (the values are mirrored in a manner color: green; explained in Chapter 14, Thinking Inside the Box). img p float: right; font-size: small; margin: 0 12px; font-family: sans-serif; /style When you are done, the document should look something like the one shown in Figure 11-4. Save the file and take a look at it in the browser. You should notice some changes (if your browser already uses a sans-serif font, you may only see size change). If not, go back and check that you included both the opening and closing curly bracket and semicolons. It’s easy to accidentally omit these characters, causing the style sheet not to work. Now we’ll change and add to the style sheet to see how easy it is to write rules and see the effects of the changes. Here are a few things to try (remember that you need to save the document after each change in order for the changes to be visible when you reload it in the browser).  Make the h1 element “gray” and take a look at it in the browser. Then make it “blue”. Finally, make it “red”. (We’ll run through the complete list of available color names in Chapter 13, Colors and Backgrounds.)  Add a new rule that makes the h2 elements red as well.  Add a 100 pixel left margin to paragraph (p) elements using this declaration: margin-left: 100px; Figure 11-4. The article after adding the small style sheet from  Remember that you can add this new declaration to the the example. As I said, not beautiful, just different. existing rule for p elements. 1 2 Part III: CSS for Presentationa How Style Sheets Work 3. Attaching the styles to the document In the previous exercise, we embedded the style sheet right in the XHTML document using the style element. That is just one of three ways that style information can be applied to an (X)HTML document. You’ll get to try each of these out soon, but it is helpful to have an overview of the methods and terminology up front. External style sheets. An external style sheet is a separate, text-only docu- ment that contains a number of style rules. It must be named with the C Commen omments ts in in S St tyle yle .css suffix. The .css document is then linked to or imported into one or S Sheets heets more (X)HTML documents (we’ll discuss how in Chapter 13). In this way, S Sometimes ometimes, , it it is is helpful helpful t to o lea leav ve e all the files in a web site may share the same style sheet. This is the most y yourself ourself or or y your our collaborat collaborators ors powerful and preferred method for attaching style sheets to content. comments comments in in a a st style yle sheet. sheet. CSS CSS has has its its o own wn comment comment syntax, syntax, sho shown wn Embedded style sheets. This is the type of style sheet we worked with in the her here: e: exercise. It is placed in a document using the style element and its rules / / comment comment goes goes here here / / apply only to that document. The style element must be placed in the C Cont ontent ent bet betw ween een the the / / and and / / will will head of the document and it must contain a type attribute that identifies be be ig ignor nored ed when when the the st style yle sheet sheet is is the content of the style element as “text/css” (currently the only available parsed parsed, , which which means means y you ou can can lea leav ve e value). This example also includes a comment (see Comments in Style comments comments an any ywher where e in in a a st style yle sheet, sheet, e ev ven en within within a a rule rule.. Sheets sidebar). body body font-size: font-size: small; small; head / / temporary temporary / / titleRequired document title here/title style type="text/css" / style rules go here / /style /head The style element may also include the media attribute used to target specific media such as screen, print, or handheld devices. These are dis- cussed in Chapter 13 as well. Inline styles. You can apply properties and values to a single element using the style attribute in the element itself, as shown here: h1 style="color: red"Introduction/h1 To add multiple properties, just separate them with semicolons, like this: h1 style="color: red; margin-top: 2em"Introduction/h1 Inline styles apply only to the particular element in which they appear. Inline styles should be avoided, unless it is absolutely necessary to over- ride styles from an embedded or external style sheet. Inline styles are problematic in that they intersperse presentation information into the structural markup. They also make it more difficult to make changes because every style attribute must be hunted down in the source. These disadvantages sound a lot like those for the obsolete font element, don’t they? Chapter 11, Cascading Style Sheets Orientation 1 3a The Big Concepts Exercise 11-2 gives you an opportunity to write an inline style and see how it works. We won’t be working with inline styles after this point for the reasons listed earlier, so here’s your chance. ex exer ercise cise 11-2 11-2 A Applying pplying an an inline inline The Big Concepts st style yle There are a few big ideas that you need to get your head around to be com- Open Open the the ar article ticle, , t tw wenties enties.html .html, , fortable with how Cascading Style Sheets behave. I’m going to introduce you in in what whate ev ver er stat state e y you ou last last lef left t it it in in to these concepts now so we don’t have to slow down for a lecture once we’re Ex Exer ercise cise 11-1. 11-1. IIf f y you ou w wor ork ked ed t to o the the rolling through the style properties. Each of these ideas will certainly be end end of of the the ex exer ercise cise, , y you ou will will ha hav ve e revisited and illustrated in more detail in the upcoming chapters. a a rule rule that that applies applies a a color color t to o the the h2 h2 elements elements.. No Now w, , wr writ ite e an an inline inline st style yle that that mak makes es Inheritance the the second second h2 h2 pur purple ple. . W We e’ll ’ll do do that that r right ight in in the the opening opening h2 h2 tag tag using using the the Are your eyes the same color as your parents’? Did you inherit their hair style style attr attribut ibute e as as sho shown wn her here: e: color? Your unique smile? Well, just as parents pass down traits to their chil- h2 h2 style="color: style="color: purple" purple" dren, (X)HTML elements pass down certain style properties to the elements Connect-the-Dots/h2 Connect-the-Dots/h2 they contain. Notice in Exercise 11-1, when we styled the p elements in a small, No Now w that that heading heading is is pur purple ple, , sans-serif font, the em element in the second paragraph became small and o ov ver err riding iding what whate ev ver er color color it it had had sans-serif as well, even though we didn’t write a rule for it specifically (Figure been been set set bef befor ore e. . T The he other other h2 h2 heading heading is is unaff unaffec ect ted ed.. 11-5). That is because it inherited the styles from the paragraph it is in. Unstyled paragraph p font-size: small; font-family: sans-serif; Paragraph with style rule applied The emphasized text (em) element is small and sans-serif even though it has no style rule of its own. It inherits the styles from the paragraph that contains it. Figure 11-5. The em element inherits styles that were applied to the paragraph. Document structure This is where an understanding of your document’s structure comes in. As I’ve noted before, (X)HTML documents have an implicit structure or hierar- chy. For example, the sample article we’ve been playing with has an html root element that contains a head and a body, and the body contains heading and paragraph elements. A few of the paragraphs, in turn, contain inline elements like images (img) and emphasized text (em). You can visualize the structure as an upside-down tree, branching out from the root, as shown in Figure 11-6. 1 Part III: CSS for Presentationa The Big Concepts html head body h1 p p h2 p p p h2 p p title style em img em em Figure 11-6. The document tree structure of the sample document, twenties.html. Parents and children The document tree becomes a family tree when it comes to referring to the relationship between elements. All the elements contained within a given element are said to be its descendants. For example, all of the h1, h2, p, em, and img elements in the document in Figure 11-6 are descendants of the body element. An element that is directly contained within another element (with no inter- vening hierarchical levels), is said to be the child of that element. Conversely, the containing element is the parent. For example, the em element is the child of the p element, and the p element is its parent. All of the elements higher than a particular element in the hierarchy are its ancestors. Two elements with the same parent are siblings. We don’t refer to “aunts” or “cousins,” so the analogy stops there. This may all seem academic, but it will come in handy when writing CSS selectors. Pass it on When you write a font-related style rule using the p element as a selector, the c c S S S S t t I I P P rule applies to all of the paragraphs in the document as well as the inline text When When y you ou lear learn n a a ne new w pr proper opert ty y, , elements they contain. We’ve seen the evidence of the em element inheriting it it is is a a good good idea idea t to o not note e whether whether the style properties applied to its parent (p) back in Figure 11-5. Figure 11-7 it it inher inherits its. . IInher nheritance itance is is not noted ed f for or demonstrates what’s happening in terms of the document structure diagram. e ev ver ery y pr proper opert ty y listing listing in in this this book book. . F For or the the most most par part, t, inher inheritance itance Note that the img element is excluded because font-related properties do not f follo ollows ws y your our expec expectations tations.. apply to images. Chapter 11, Cascading Style Sheets Orientation 1a The Big Concepts html head body h1 p p h2 p p p h2 p p title style em img em em p font-size: small; font-family: sans-serif; Figure 11-7. Certain properties applied to the p element are inherited by their children. Notice that I’ve been saying “certain” properties are inherited. It’s important to note that some style sheet properties inherit and others do not. In gen- eral, properties related to the styling of text—font size, color, style, etc.—are passed down. Properties such as borders, margins, backgrounds, and so on that affect the boxed area around the element tend not to be passed down. This makes sense when you think about it. For example, if you put a border around a paragraph, you wouldn’t want a border around every inline element (such as em, strong, or a) it contains as well. You can use inheritance to your advantage when writing style sheets. For example, if you want all text elements to be rendered in the Verdana font face, you could write separate style rules for every element in the document and set the font-face to Verdana. A better way would be to write a single style rule that applies the font-face property to the body element, and let all the text elements contained in the body inherit that style (Figure 11-8). If you apply a font-related property to the body element, it will be passed down to all the text elements in the document (note that font properties do not apply to the img element, so it is excluded). html head body h1 p p h2 p p p h2 p p title style em img em em p font-size: small; font-family: sans-serif; Figure 11-8. All the elements in the document inherit certain properties applied to the body element. 1 Part III: CSS for Presentationa The Big Concepts Any property applied to a specific element will override the inherited values for that property. Going back to the article example, we could specify that the em element should appear in a serif font, and that would override the inherited sans-serif setting. Conflicting styles: the cascade Ever wonder why they are called “cascading” style sheets? CSS allows you to apply several style sheets to the same document, which means there are bound to be conflicts. For example, what should the browser do if a document’s imported style sheet says that h1 elements should be red, but its embedded style sheet has a rule that makes h1s purple? The folks who wrote the style sheet specification anticipated this problem and devised a hierarchical system that assigns different weights to the vari- R Reader eader S St tyle yle S Sheets heets ous sources of style information. The cascade refers to what happens when IIt t is is possible possible f for or users users t to o wr writ ite e their their several sources of style information vie for control of the elements on a page: o own wn st style yle sheets sheets and and apply apply them them t to o the the pages pages the they y see see with with their their style information is passed down until it is overridden by a style command br bro owser wser. . T The he CSS CSS R Recommendation ecommendation with more weight. r ref efers ers t to o these these as as r reader eader st style yle sheets sheets (in (in prac practice tice, , it it is is mor more e common common t to o For example, if you don’t apply any style information to a web page, it will be use use the the t ter erm m user user st style yle sheets sheets). ). rendered according to the browser’s internal style sheet (we’ve been calling Nor Normally mally, , st style yle rules rules pr pro ovided vided b by y this the default rendering). However, if the web page’s author provides a style an an author author st style yle sheet sheet ( (ex ext ter ernal nal, , sheet for the document, that has more weight and overrides the browser’s embedded embedded, , or or inline) inline) o ov ver err ride ide the the styles. Individual users can apply their own styles to documents as well, as r reader eader’’s s st style yle sheet. sheet. Ho How we ev ver er, , if if the the discussed in the Reader Style Sheets sidebar. user user mar marks ks a a st style yle as as “ “impor important, tant,” ” it it will will trump trump all all other other st styles yles pr pro ovided vided As we’ve learned, there are three ways to attach style information to the source b by y the the author author and and the the br bro owser wser (see (see the the A Assig ssigning ning IImpor mportance tance sidebar). sidebar). document, and they have a cascading order as well. Generally speaking, the closer the style sheet is to the content, the more weight it is given. Embedded S So o, , f for or example example, , a a user user with with impair impaired ed vision vision could could wr writ ite e a a st style yle rule rule style sheets that appear right in the document in the style element have that that mak makes es all all w web eb t tex ext t appear appear in in more weight than external style sheets. In the example that started this sec- ex extra tra lar large ge black black t tex ext t on on a a whit white e tion, the h1 elements would end up purple as specified in the embedded style back backg gr round ound and and be be guarant guaranteed eed t to o sheet, not red as specified in the external .css file that has less weight. Inline see see it it that that wa way y. . T That hat’’s s pr precisely ecisely the the W3C W3C’’s s int intent ent in in allo allowing wing r reader eader st style yle styles have more weight than embedded style sheets because you can’t get any sheets sheets and and g giving iving them them the the po pow wer er closer to the content than a style right in the element’s opening tag. t to o o ov ver err ride ide all all other other st styles yles.. To prevent a specific rule from being overridden, you can assign it “importance” with the important indicator, as explained in the Assigning Importance sidebar. The sidebar, Style Sheet Hierarchy, provides an overview of the cascading order from general to specific. Specificity Once the applicable style sheet has been chosen, there may still be conflicts; therefore, the cascade continues at the rule level. When two rules in a single style sheet conflict, the type of selector is used to determine the winner. The Chapter 11, Cascading Style Sheets Orientation 1a The Big Concepts Assigning Importance If you want a rule not to be overridden by a subsequent conflicting rule, include the important indicator just after the property value and before the semicolon for that rule. For example, to make paragraph text blue always, use the following rule: p color: blue important; Even if the browser encounters an inline style later in the document (which should override a document-wide style sheet), like this one: p style="color: red" that paragraph will still be blue, because the rule with the important indicator cannot be overridden by other styles in the author’s style sheet. The only way an important rule may be overridden is by a conflicting rule in a reader (user) style sheet that has also been marked important. This is to ensure that special reader requirements, such as large type for the visually impaired, are never overridden. Based on the previous examples, if the reader’s style sheet includes this rule: p color: black; the text would still be blue, because all author styles (even those not marked important) take precedence over the reader’s styles. However, if the conflicting reader’s style is marked important, like this: S St tyle yle S Sheet heet p color: black important; H Hier ierar arch chy y the paragraphs will be black and cannot be overridden by any author-provided style. St Style yle inf infor ormation mation can can come come fr from om var various ious sour sources ces, , list listed ed her here e fr from om general general t to o specific specific. . IIt tems ems lo low wer er in in more specific the selector, the more weight it is given to override conflicting the the list list will will o ov ver err ride ide it items ems abo abov ve e declarations. them: them:  Br Bro owser wser default default settings settings It’s a little soon to be discussing specificity because we’ve only looked at one  User User st style yle settings settings (set (set in in a a type of selector (and the least specific type, at that). For now, put the term br bro owser wser as as a a “ “r reader eader st style yle sheet sheet”) ”) specificity and the concept of some selectors overriding others on your radar.  Link Linked ed ex ext ter ernal nal st style yle sheet sheet We will revisit it in Chapter 12 when you have more selector types under (added (added with with the the link link element) element) your belt.  IImpor mport ted ed st style yle sheets sheets (added (added with with the the import import Rule order func function) tion)  Embedded Embedded st style yle sheets sheets Finally, if there are conflicts within style rules of identical weight, whichever (added (added with with the the style style element) element) one comes last in the list “wins.” Take these three rules, for example:  IInline nline st style yle inf infor ormation mation style type="text/css" (added (added with with the the style style attr attribut ibute e p color: red; in in an an opening opening tag) tag) p color: blue;  An Any y st style yle rule rule mar mark ked ed important important p color: green; b by y the the author author /style  An Any y st style yle rule rule mar mark ked ed important important In this scenario, paragraph text will be green because the last rule in the style b by y the the r reader eader (user) (user) sheet, that is, the one closest to the content in the document, overrides the earlier ones. 1 Part III: CSS for Presentationa The Big Concepts N ot e This “last-one-listed wins” rule applies in other contexts in CSS as well. For example, later declarations in a declaration block can override earlier declarations. In addition, external style sheets listed later in the source will be given precedence over those listed above them (even style sheets embedded with the style element). The box model As long as we’re talking about “big CSS concepts,” it is only appropriate to introduce the cornerstone of the CSS visual formatting system: the box model. The easiest way to think of the box model is that browsers see every element on the page (both block and inline) as being contained in a little rectangular box. You can apply properties such as borders, margins, padding, and backgrounds to these boxes, and even reposition them on the page. We’re going to go into a lot more detail about the box model in Chapter 14, but having a general feel for the box model will benefit you even as we discuss text and backgrounds in the following two chapters. To see the elements roughly the way the browser sees them, I’ve written style rules that add borders around every content element in our sample article. h1 border: 1px solid blue; h2 border: 1px solid blue; p border: 1px solid blue; em border: 1px solid blue; img border: 1px solid blue; Figure 11-9 shows the results. The borders reveal the shape of each block ele- ment box. There are boxes around the inline elements (em and img), as well. Notice that the block element boxes expand to fill the available width of the browser window, which is the nature of block elements in the normal docu- ment flow. Inline boxes encompass just the characters or image they contain. Figure 11-9. Rules around all the elements reveal their element boxes. Chapter 11, Cascading Style Sheets Orientation 1a Moving Forward with CSS Grouped Selectors Hey This is a good opportunity to show you a handy style rule shortcut. If you ever need to apply the same style property to a number of elements, you P Po op p Q Qu ui iz z can group the selectors into one rule by separating them with commas. This one rule has the same effect as the five rules listed previously. Grouping them C Can an y you ou guess guess wh why y I I didn didn’’t t just just add add the the border border pr proper opert ty y t to o the the body body makes future edits more efficient and results in a smaller file size. element element and and let let it it inher inherit it t to o all all the the h1, h2, p, em, img border: 1px solid blue; elements elements in in the the g gr rouped ouped selec select tor? or? Now you’ve got two selector types in your toolbox: a simple element selector, A Answ nswer: er: and grouped selectors. Moving Forward with CSS This chapter covered all the fundamentals of Cascading Style Sheets, includ- ing rule syntax, ways to apply styles to a document, and the central concepts of inheritance, the cascade, and the box model. Style sheets should no longer be a mystery, and from this point on, we’ll merely be building on this founda- tion by adding properties and selectors to your arsenal as well as expanding on the concepts introduced here. CSS is a vast topic, well beyond the scope of this book. The bookstores and Web are loaded with information about style sheets for all skill levels. I’ve compiled a list of the resources I’ve found the most useful during my learning process. I’ve also provided a list of popular tools that assist in writing style sheets in the CSS Tools sidebar. Books There is no shortage of good books on CSS out there, but these are the ones that taught me, and I feel good recommending them. Cascading Style Sheets: The Definitive Guide, Second Edition, by Eric Meyer (O’Reilly) Web Standards Solutions: The Markup and Style Handbook, by Dan Cederholm (Friends of Ed) The Zen of CSS Design: Visual Enlightenment for the Web, by Dave Shea and Molly E. Holzschlag (New Riders) Eric Meyer on CSS: Mastering the Language of Web Design, by Eric Meyer (New Riders) Online Resources The sites on the following page are good starting points for online explora- tion of style sheets. 200 Part III: CSS for Presentation B Because ecause border border is is one one of of those those pr proper operties ties that that is is not not inher inherit ited ed, , as as not noted ed ear earlier lier..a Moving Forward with CSS World Wide Web Consortium (www.w3.org/Style/CSS) The World Wide Web Consortium oversees the development of web tech- nologies, including CSS. A List Apart (www.alistapart.com) CSS CSS T Tools ools This online magazine features some of the best thinking and writing on cutting-edge, standards-based web design. It was founded in 1998 by T The he W3C W3C maintains maintains a a list list of of cur curr rent ent CSS CSS author authoring ing t tools ools on on the the CSS CSS Jeffrey Zeldman and Brian Platz. home home page page at at w ww ww w.w3.or .w3.org/St g/Style/ yle/ css-discuss (www.css-discuss.org) CSS/edit CSS/editors ors. . Her Here e ar are e a a couple couple that that I I can can personally personally r recommend ecommend. . This is a mailing list and related site devoted to talking about CSS and how to use it. W Web eb De Dev veloper eloper Ex Ext tension ension Inspirational CSS showcase sites W Web eb de dev velopers elopers ar are e ra raving ving about about the the W Web eb D De ev veloper eloper ex ext tension ension f for or If you are looking for excellent examples of what can be done with CSS, check F Fir iref efo ox x and and M Mo ozilla zilla br bro owsers wsers, , wr writt itten en out these sites. b by y Chr Chris is P Peder ederick ick. . T The he ex ext tension ension adds adds a a t toolbar oolbar t to o the the br bro owser wser with with CSS Zen Garden (www.cssgarden.com) t tools ools that that enable enable y you ou t to o analyz analyze e and and This is a showcase site for what can be done with CSS, a single XHTML manipulat manipulate e an any y page page in in the the windo window w. . Y You ou can can edit edit the the st style yle sheet sheet f for or the the file, and the creative ideas of hundreds of designers. Its creator and keeper page page y you ou ar are e vie viewing wing as as w well ell as as get get is standards expert Dave Shea. See the companion book listed above. inf infor ormation mation about about the the ( (X)HTML X)HTML and and g graphics raphics. . IIt t also also validat validates es the the CSS, CSS, CSS Beauty (www.cssbeauty.com) ( (X)HTML, X)HTML, and and accessibilit accessibility y of of the the A showcase of excellent sites designed in CSS. page page. . G Get et it it at at chrisp chrispederick ederick.c .com/ om/ w work/fir ork/firefo efox/w x/web ebdev develop eloper er or or fr from om the the A Addons ddons page page at at mo mozilla.or zilla.org g.. Informative personal sites Some of the best CSS resources are the blogs and personal sites of individuals W Web eb A Authoring uthoring P Pr rog ogr rams ams with a passion for CSS-based design. These are only a few, but they provide a C Cur urr rent ent WY WYSIWY SIWYG G author authoring ing good entry point into the online standards community. pr prog ograms rams such such as as A Adobe dobe Stopdesign (www.stopdesign.com) Dr Dream eamw wea eav ver er and and M Micr icrosof osoft t Expr Expression ession W Web eb can can be be configur configured ed Douglas Bowman, CSS and graphic design guru, publishes articles and t to o wr writ ite e a a st style yle sheet sheet f for or y you ou trend-setting tutorials. aut automatically omatically as as y you ou desig design n the the page page. . T The he do downside wnside is is that that the they y Mezzoblue (www.mezzoblue.com) ar are e not not alwa always ys wr writt itten en in in the the most most This is the personal site of Dave Shea, creator of the CSS Zen Garden. efficient efficient manner manner (f (for or example example, , the they y t tend end t to o o ov veruse eruse the the class class attr attribut ibute e Meyerweb (www.meyerweb.com) t to o cr creat eate e st style yle rules). rules). Still Still, , the they y ma may y g giv ive e y you ou a a good good head head star start t on on the the This is the personal site of the king of CSS, Eric Meyer. st style yle sheet sheet that that y you ou can can then then edit edit manually manually.. Molly.com (www.molly.com) This is the blog of prolific author and web-standards activist Molly E. Holzschlag. Simplebits (www.simplebits.com) This is the personal site of standards guru and author Dan Cederholm. Chapter 11, Cascading Style Sheets Orientation 201a Test Yourself Test Yourself Here are a few questions to test your knowledge of the CSS basics. Answers are provided in Appendix A. 1. Identify the various parts of this style rule: blockquote line-height: 1.5; selector: _______________ value: ____________________ property: ______________ declaration: ________________ 2. What color will paragraphs be when this embedded style sheet is applied to a document? Why? style type="text/css" p color: purple; p color: green; p color: gray; /style 3. Rewrite each of these CSS examples. Some of them are completely incor- rect and some could just be written more efficiently. a. p font-face: sans-serif; p font-size: 1em; p line-height: 1.2em; b. blockquote font-size: 1em line-height: 150% color: gray c. body background-color: black; color: 666; margin-left: 12em; margin-right: 12em; d. p color: white; blockquote color: white; li color: white; e. strong style="red"Act now/strong html 4. Circle all the elements in the diagram that you would expect to appear in red when the head body following style rule is applied to an XHTML document with the structure diagrammed in title style h1 div id= intro div id= main p Figure 11-10. This rule uses a type of selec- tor you haven’t seen yet, but common sense p ul h2 p h2 p should serve you well. divintro color: red; img strong li li li Figure 11-10. The document structure of a sample document. 202 Part III: CSS for Presentationa 12 CHAPTER FORMATTING TEXT (Plus More Selectors) Now that you’ve gotten your feet wet formatting text, are you ready to jump IN THIS CHAPTER into the deep end? By the end of this chapter, you’ll pick up fourteen new CSS The font-related properties properties used to manipulate the appearance of text. Along the way, you’ll also learn how to use more powerful selectors for targeting elements in a Text color particular context, and with a specific id or class name. Text line settings such as line height, indents, Throughout this chapter, we’ll be sprucing up the Black Goose Bistro online and alignment menu that we marked up back in Chapter 5, Marking Up Text. I encourage you to work along with the exercises to get a feel for how the properties Underlines and overlines work. Figure 12-1 shows how the menu looked the last time we saw it and Capitalization how it will look when we’re done. It’s not a masterpiece, but it is certainly an improvement. Letter and word spacing Descendant (contextual), ID, and class selectors Specificity 101 Before After Figure 12-1. Before and after views of the Black Goose Bistro menu that we’ll be working on in this chapter. 203a The Font Properties The Font Properties A A t t A A G G l l A A n n c c e e When I design a text document (especially for print, but also for the Web), T The he f font ont-r -relat elated ed pr proper operties: ties: one of the first things I do is specify the font. In CSS, fonts are specified using  font-family font-family a little bundle of font-related properties for typeface, size, weight, and font  font-size font-size style. There is also a shortcut property that lets you specify all of the font  font-weight font-weight attributes in one fell swoop.  font-style font-style The nature of the Web makes specifying type tricky, if not downright  font-variant font-variant frustrating, particularly if you have experience designing for print (or even  font font formatting text in a word processing program). Because you have no way of knowing which fonts are loaded on users’ machines, you can’t be sure that everyone will see text in the font you’ve chosen. And because the default font size varies by browser and user preferences, you can’t be sure how large or A A W Wor ord d A About bout small the type will appear, as well. We’ll address the best practices for dealing P Pr roper opert ty y Listings Listings with these font challenges as we go along. Each Each ne new w pr proper opert ty y listing listing in in this this book book is is accompanied accompanied b by y inf infor ormation mation on on ho how w it it beha behav ves es and and ho how w t to o use use it. it. Specifying the font name Her Here e is is a a quick quick explanation explanation of of each each Choosing a typeface, or font family as it is called in CSS, is a good place to par part t of of pr proper opert ty y listings listings.. start. Let’s begin with the easy part: using the property font-family and its V Values alues values. T These hese ar are e the the accept accepted ed values values f for or the the pr proper opert ty y accor according ding t to o the the font-family CSS2.1 CSS2.1 specification. specification. P Pr redefined edefined Values: one or more font or generic font family names, separated by commas inherit values values appear appear in in code code f font ont Default: depends on the browser (f (for or example example, , small small, , italic italic, , or or Applies to: all elements small-caps small-caps) ) and and must must be be t typed yped in in exac exactly tly as as sho shown. wn. Inherits: yes Use the font-family property to specify a font or list of fonts by name as D Def efault ault shown in these examples. T Th hiis s iis s t th he e v va allu ue e t th ha at t w wiillll b be e u us se ed d f fo or r t th he e p pr ro op pe er rt ty y b by y d de ef fa au ullt t,, t th ha at t iis s, , body font-family: Arial; iif f n no o o ot th he er r v va allu ue e iis s s sp pe ec ciif fiie ed d.. N No ot te e tt font-family: Courier, monospace; t th ha at t t th he e b br ro ow ws se er r u us se es s a a s st ty ylle e s sh he ee et t p font-family: "Trebuchet MS", Verdana, sans-serif; w wiit th h v va allu ue es s t th ha at t m ma ay y v va ar ry y f fr ro om m t th he e d de ef fa au ullt ts s d de ef fiin ne ed d iin n C CS SS S.. All font names, with the exception of generic font families, must be capital- ized. For example, use “Arial” instead of “arial”. Notice that font names that A Applies pplies t to o contain a character space (such as Trebuchet MS in the third example) must S Some ome pr proper operties ties apply apply only only t to o appear within quotation marks. Use commas to separate multiple font names cer certain tain t types ypes of of elements elements, , such such as as as shown in the second and third examples. You might be asking, “Why block block or or table table elements elements.. specify more than one font?” That’s a good question, and it brings us to one Inherits Inherits of the challenges of specifying fonts for web pages. T This his indicat indicates es whether whether the the pr proper opert ty y will will be be passed passed do down wn Font limitations t to o the the selec select ted ed element element’’s s descendants descendants. . S See ee Chapt Chapter er Browsers are limited to displaying fonts that are already installed on the user’s 11, 11, C Cascading ascading St Style yle Sheets Sheets machine. So, although you may want the text to appear in Futura, if Futura Or Orientation ientation f for or an an explanation explanation of of is not installed on the user’s computer, the browser’s default font will be used inher inheritance itance.. instead. 20 Part III: CSS for Presentationa The Font Properties Fortunately, CSS allows you to provide a list of back-up fonts should your first choice not be available. In the third example above, if the browser does not find Trebuchet MS, it will use Verdana, and if Verdana is not available, it will substitute some other sans-serif font. Generic font families That last option, “some other sans-serif font,” bears more discussion. “Sans- All All o of f the the f font ont pr properties operties serif” is just one of five generic font families that you can specify with the ar are e r rela elat ted ed t to o the the shapes shapes font-family property. When you specify a generic font family, the browser o of f char charact acters. ers. chooses an available font from that stylistic category. Figure 12-2 shows examples from each family. Generic font family names do not need to be capitalized. serif Examples: Times, Times New Roman, Georgia Serif typefaces have decorative serifs, or slab-like appendages, on the ends of certain letter strokes. sans-serif Examples: Arial, Arial Black, Verdana, Trebuchet MS, Helvetica, Geneva Sans-serif typefaces have straight letter strokes that do not end in serifs. They are generally considered easier to read on computer monitors. monospace Examples: Courier, Courier New, and Andale Mono In monospace (also called constant width) typefaces, all characters take up the same amount of space on a line. For example, a capital W will be no wider than a lowercase i. Compare this to proportional typefaces (such as the one you’re reading now) that allot different widths to different char- acters. cursive Examples: Apple Chancery, Zapf-Chancery, and Comic Sans Cursive fonts emulate a script or handwritten appearance. These are rarely specified for professional web pages. fantasy Examples: Impact, Western, or other decorative font Fantasy fonts are purely decorative and would be appropriate for head- lines and other display type. Fantasy fonts are rarely used for web text due to cross-platform availability and legibility. Chapter 12, Formatting Text 20a The Font Properties Decorative Serif serif stroke Times Georgia Times New Roman Lucida (Mac) Straight Sans-serif strokes Veranda Trebuchet MS Arial Arial Black Monospace Courier Monospace font Proportional font Courier New Andale Mono (equal widths) (different widths) Cursive Apple Chancery Comic Sans Snell Fantasy Imapct Stencil Mojo Figure 12-2. Examples of the five generic font families. Font specifying strategies The best practice for specifying fonts for web pages is to start with your first D D e e S S I I G G n n t t I I P P choice, provide some similar alternatives, then end with a generic font family Y You ou’ll ’ll find find that that the the major majorit ity y of of that at least gets users in the right stylistic ballpark. Here’s another example pr prof ofessional essional w web eb sit sites es use use V Ver erdana dana of this strategy in action. With this style rule, I specify that I’d prefer that users because because it it was was specially specially desig designed ned t to o see all the text in Verdana, but I’d settle for Arial, or Helvetica, or, if all else be be leg legible ible at at small small siz sizes es on on comput computer er monit monitors ors. . T This his is is a a common common value value fails, I’ll let the browser choose an available sans-serif font for me. line line-up -up f for or font-family font-family:: body font-family: Verdana, Arial, Helvetica, sans-serif; Verdana, Verdana, Arial, Arial, sans-serif sans-serif Because a font will only show up if it’s on a user’s hard drive, it makes sense to specify fonts that are the most commonly available. Although there are countless fonts out there, the fact is that because licensed copies of fonts cost big bucks, most users stick with the fonts that are installed by their operating 20 Part III: CSS for Presentation

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.