Вы находитесь на странице: 1из 41

Core CSS: Part I

By Molly E. Holzschlag

About CSS
As Cascading Style Sheets mature as a language of design and a tool of Web site and application management, a deep understanding of ho the language really or!s is essential. Ho e"er, most people ha"e learned CSS the same ay they#"e learned H$M%,by "ie ing source, copying template codes, reading boo!s and articles. While this &bootstrap& method of learning is often the best ay to find great techni'ues, it may not be the best for !no ing ho to manage, debug, customize and e"en ad"ance those techni'ues. What our training hasn#t necessarily pro"ided are the core concepts ithin CSS. $his is hy the Core CSS series may contain simple e(amples of things you already !no . )ou#ll *ust get to !no them better here+ ,n this foundational reference card, you#ll find not only a bit of history and rationale for use, rule structure and synta(, but also a thorough resource as to the Cascade, inheritance and specificity,core principles of CSS that ill e(pand and strengthen your professional ability to or! ith CSS.

CSS Rationale and Use


$he idea behind CSS is not a ne one. We#"e seen the separation of presentation before in des!top publishing, here master style sheets can be created to control the layout, typefaces and colors used in a gi"en design. Cascading Style Sheets ere concei"ed to do e(actly that- .emo"e the style from the document and place it separately from the code to be styled. $he benefits, hen used carefully, can be outstanding. Some benefits of using style sheets include Design flexibility More image options Better typographic control /ar more fle(ible layout options 0rint design support Handheld de"ice design support Easier site maintenance 1ne style sheet, infinite pages 2esign changes are "ery easy Changes can be made 'uic!ly .educes time to launch Measurable returns /aster loading documents /ar smaller documents 3ser e(perience impro"es Accessibility impro"es SE1 4search engine optimization5 impro"es $he first proposal for CSS as made by H6!on Wium %ie, no C$1 of 1pera Soft are. He or!ed ith Bert Bos to co7author the first CSS specification, hich belie"e it or not, became a

recommendation in 899:+ By 899; CSS <.= brought us richer options, as e find later in ad"ancing "ersions CSS <.8 and CSS >.=. Date Im lementations /irst proposed 899?, /irst CSS 8.= Still fla ed CSS 8 portions in all CSS bro sers specification in 899: CSS <.= 899; @o full implementation @ot yet published as a complete CSS <.8 Some close to complete implementations specification CSS >.= Certain modules are ahead of Some CSS >.= features are implemented in "ersions of 4Modular5 others in de"elopment WebAit, Mozilla and 1pera bro sers !able "# CSS Bersions, 0ublication 2ates and ,mplementation As CSS e"ol"es, e find it becoming more and more important for not only "isual designers in terms of managing the esthetics of the site, but technologists or!ing on large eb sites or loo!ing to create roc!7solid applications. Version

A Se arate Piece
$he term for sites designed using table7based layouts and H$M% presentation rather than CSS are referred to as being authored in presentational H$M%. $his means that the presentation 4the design, style, and layout5 isn#t separated from the mar!up 4content ith basic formatting5. Consider this header, hich contains elements and attributes that define presentation<h1><font size="5" color="red" face="Arial, Helvetica, sans-serif">Welcome!</font></h1>

3sing presentational H$M%, e"ery time you need a ne font size, color or face it has to be e(plicitly defined in that document. And then redefined. ,n CSS, e can set up presentation and ha"e it used not only multiple times ithin a gi"en document, but across literally millions of documents. So, if , instead had a separate style sheet ith this ruleh1 {font-size !"#$ color red$ font-famil% Arial, Helvetica, sans-serif$&

E"ery single document , ant to apply this style to can be attached to this sheet. $hen, if , need to change a million documents ith an h8 of red to an h8 of green, , simply go to the one style sheet, change the color in one location, one time, sa"e the style and instantly all the documents connected to the sheet ill no ha"e green h8 headers 4this is the point here you tell the boss it#s going to ta!e all day to ma!e the change, grab your stuff, and head to the beach5+ So from the get7go the principles of CSS suggest that e gain many benefits from separating the technology layers that ma!e up front end Web de"elopment- 2ocument, presentation, beha"ior 4/igure 85.

$igure "# 2ocument 4mar!upCcontent5D 0resentation 4CSS5D Beha"ior 4Ea"aScript5 1f course, *ust because e &ba!e& our three7layered ca!e separately, it all has to come together and *ust be &ca!e& at some point+ $his is here standards7based design and best practices come significantly into play, and of course those s!ills rely in turn on 'uality learning in terms of both the languages and Web bro sers e use.

%earning and Im lementation Cur&es


Ho e"er, there#s been difficulty along the road to adopting, learning and managing CSS. $his difficulty is due to a number of influences, but t o of the ma*or concerns are a steep learning cur"e and lac! of consistent bro ser implementation of specifications. Especially of challenge for "isual designers is that CSS nomenclature and concepts are programmatic rather than graphic7design oriented 4$able <5 and there are no tools that can fully replace designer understanding. A fun, if not frightening metaphor ould be to as! graphic designers if they code in postscript, the underlying language for "ector dra ing in Adobe products. CSS !erm 'ra (ic Design Meaning line7height %eading Space bet een lines font7family $ypeface 3sed to describe specific type faces such as Hel"etica color $ype color $he color of the te(t characters Multiple meanings ithin /or 2ream ea"er users, a layer is actually an absolutely layer soft are tools positioned element. F/// White White !able )# Brief Comparison of terminology in "isual design and CSS At first glance it#s easy to thin! that these are simple issues and 'uic!ly remedied. But it is undeniable that the lac! of clarity in terminology has led to a steeper learning cur"e than using a table 4grid5 and then presentational elements to or! ith that grid,much more intuiti"e to designers ho ere taught traditional grid, color and typographic design. ,f you use 2ream ea"er, a"oid using 2ream ea"er#s %ayers 4a term that#s been dropped from CS?, than!fully5, as they use style in a less7than best case scenario. While this feature can be helpful for ireframing, it can be do nright disastrous in li"e sites. .e"ie topics such as positioning and CSS floats for alternati"es to this feature. $hat there#s a lac! of consistent and ell7paced implementation in Web bro sers and other user soft are is sadly ell !no n, ma!ing actual use of CSS a combination of good code riddled ith

or!arounds, hac!s, filters and Ea"aScript patch or! to repair problems across bro ser and bro ser "ersions. Error handling is a particularly frustrating part of this, particularly as Web bro sers implement different "ersions of different specifications at different times 4/igure <5.

$igure )# Error handling in bro sers. ,n the first instance, if there#s a mista!e in the rule, the bro ser simply drops the erroneous rule and re"erts to the bro ser style. ,n the second instance, the bro ser instead ma!es an attempt to find a nearest "alue and apply the color to nearly disastrous results. $his is hy learning as much as you can about ho CSS or!s is so empo ering. As you begin to understand that most frustration ith CSS is not your fault and learn some techni'ues to or! ith some of CSS#s comple(ities, you#ll be able to reduce the frustration caused by certain bro ser differences, CSS implementation, and be able to focus on the use of CSS for design and documentGapplication management.

Understanding Style Rule Syntax


We#ll ta!e a loo! at rule synta( here, hich ill set you up to 'uic!ly understand the basic structure of CSS as e discuss rules in the conte(t of other language issues. A CSS rule contains at least one selector and at least one declaration ithin a declaration bloc!. A declaration is made up of a property name and a corresponding "alue. 2eclaration bloc!s are defined by curly brac!ets &HI& and declarations are separated ith a semicolonh1 {color red$&

$his rule in turn has the bro ser find a match to the h8 selector and gi"e it a color of red 4/igure >5.

$igure *# 3sing the h8 selector to apply the color &red& to a corresponding h8 element Additional declarations are simply added to the bloc!h1 {color red$ font-size !"#$ font-famil% 'erdana$&

this rule as!s the bro ser to match any h8, color it red, size it relati"ely to ;=J and apply the Berdana typeface 4/igure ?5-

$igure +# Adding additional declarations to the rule. Pur ose Exam les h1 A selector chooses 4&selects&5 an element ithin (content mar!up documents to be styled. $here are many )mod*le Selector selector types in CSS <.8, and e"en more to hover come in future years. A declaration is made up of a CSS property and a related property "alue. CSS properties are color red$ numerous and define "arious styles as they font-variant small ca+s$ relate to colors, te(t, positioning, margins, mar,in " " "$ 2eclaration padding, and positioning. A declaration can ha"e -ac.,ro*nd-ima,e /m%)0+,1$ as many property and "alue pairs as you li!e, contained as a group in a declaration bloc! and separated ith a semi7colon &D& 2eclaration Multiple declarations related to a gi"en selector Bloc! are referred to as a 2eclaration Bloc!.
{color red$ font-variant small ca+s$ mar,in " " "$ -ac.,ro*nd -ima,e /m%)0+,1$ & )mod*le {color red$ fontvariant small ca+s$ mar,in " " "$ -ac.,ro*nd -ima,e /m%)0+,1$ &

'rammar

CSS .ule

A selector plus a declaration or declaration bloc! ma!es a CSS rule.

Style Sheet Any set of style rules !able *# .ule Synta( in CSS

4See &Style Sheet $ypes& later in this reference5

1nce again, bear in mind that there are many selector, property, and property "alue types. )ou#ll or! ith many of them ithin the series, and be sure to loo! for the online references pro"ided so you#ll ha"e plenty of resources.

In(eritance
,t#s important to !no that many properties and associated "alues are inherited. ,t#s a fairly simplistic concept, simply relate it to hat you !no about inheritance in li"ing beings. , ha"e my mother#s curly hair, the shape of my father#s eyes. And, *ust as e could map out a family tree and see here some of those features came from, so can e use the document tree to do the same 4/igure K5.

$igure ,# ,nheritance. ,magine pouring a buc!et of blue paint onto the body element. Because color is an inheritable property, all te(t descending from body ill be blue until another style o"errides the inherited color. Some properties are not inheritable, mostly those related to the bo( model 4margins, padding, bo( idths and so on5, ho e"er most are. Authors can tap into the po er of inheritance by allo ing inheritable properties to be inherited by their children or descendents, or prohibit inheritance if so desired.

Style S(eet !y es
$here are three primary types of style sheets as follo s -ro.ser# $he bro ser style sheet is the default style of a gi"en bro ser. ,t is either an actual .css file such as e find in Mozilla bro sers, or hard coded into the soft are. Bro ser styles are different bet een bro sers and "ersions, so being a are of them is e(tremely important. Where"er you do not supply a style, the bro ser style ill be used instead. User# 3ser style sheets are a great concept that has unfortunately not been brought to bear on a large scale. 3ser styles are meant for accessibility purposes. My aging eyes re'uire larger te(t and higher contrast, , can rite a 'uic! style sheet to address my issues and apply it "ia the bro ser. Aut(or# $he author is you+ $hat is, author styles are those styles that the de"eloper or designer is in charge of creating to create the design and management scenarios for a gi"en Web site or application. At some point you might ha"e come across the +important 4referred to as &bang important&5 !ey ords. $he proper use for +important is to create a balance bet een author and user style sheets, a necessity for accessibility purposes. ,f used in an author style sheet but not a user style sheet, the author#s rule is considered to ha"e more eight and therefore ill apply. Because of this, +important is useful only in t o places- As a diagnostic tool hich you remo"e from the declaration after debugging a problemD and in a user style sheet. 1ther ise, please a"oid usage at all costs.

Aut(or Style S(eets by !y e


$here are three types of author style sheets- ,nline, embedded and lin!ed 4e(ternal5. Each is authored differently and has different applications, benefits, and concerns. Inline Style ,nline style is style that is used directly in the mar!up document to style one discrete element. @o matter hat other style sheets might be influencing the document, an inline style is considered more specific and therefore ill apply to that element no matter other conflicting styles. Consider the follo ing paragraph element<+>2his +ara,ra+h is st%led onl% -% defa*lt -ro3ser st%les</+>

$he style is placed ithin the style attribute as a "alue<+ st%le="color -l*e$">2his +ara,ra+h 3ill no3 have a -l*e color)</+>

/igure : sho s the comparison.

$igure /# Applying style to a discrete element using inline style. ,f you#re thin!ing &but that code really loo!s *ust li!e presentational mar!up+& gi"e yourself a big pat on the bac!. ,n recent years, many people, including those at the W>C responsible for ad"ancing mar!up and CSS, ha"e ad"ised that using this techni'ue isn#t really separating presentation from the document at all+ So hat benefits does inline style really offerL $able ? pro"ides some best practice insights as to hen to a"oid and hen to use inline style. Issues ,f you ha"e a "ery small site 48= documents or ,nline style in less5 the ris! of losing trac! of inline styles is small "ersus less than if you are or!ing on "ery large large Web sites, here it#s easy to lose trac! of inline sites styles unless they are meticulously documented. And ho does thatL As the section on &specificity& ill demonstrate, an inline style has the highest specificity of any other rule that might be ,nline style trying to style the element in 'uestion. ,f you for debugging are ha"ing trouble getting to the heart of the purposes matter, dropping an inline style into the element you are ha"ing trouble ith can help determine that in fact, there#s a conflict. Scenario -est Practice A"oid use of inline style in almost all professional eb sites, and in particular those sites hich are large or e(pected to gro significantly. 3se inline style hen necessary to debug. $ypically, if you are able to apply a style inline that you#d been struggling ith before means you ha"e rules conflicting some here that need to be found. /ind the conflicts, repair the rules, and remo"e the diagnostic inline style prior to publishing+

Issues -est Practice $here are "ery fe benefits from using inline ,nline style as 2espite the fact that , do this myself, it#s style, but one , find that#s great is for 'uic! &'uic!& fi(es not something ,#d recommend, fi(es and blog posts, hich you can do on the 4a!a laziness5 particularly for professional sites. fly. !able +# Best 0ractices- ,nline Style Embedded Style Embedded style is used to control the style of a single document. ,n this case, the style element is used to define the embedded area for the document#s style as follo s<!4562789 html 8:;<=6 --//W>6//424 ?H2@< 1)" Atrict//9B"htt+ //333)3>)or,/2C/Dhtml1/424/Dhtml1-strict)dtd"> <html Dmlns="htt+ //333/3>/or,/2C/Dhtml1"> <head> <title>6ore 6AA = 9Dam+les</title> <st%le t%+e="teDt/css"> + {color -l*e$& </st%le> </head> <-od%> <+>=n this case, all +ara,ra+hs on the +a,e 3ill t*rn -l*e)</+> </-od%> </html>

Scenario

So as ith inline style, e#re left loo!ing at a type of style sheet that, hile handy in some cases, doesn#t pro"ide the benefits e#re loo!ing for. With the style element in the head portion of the document, e do achie"e slightly better separation of presentation from our document#s content and structure, but only in that same document. $able K pro"ides some insights into the best ays to use embedded style. Issues -est Practice ,f you ha"e a eblog ith one template document that controls your entire site, it is Embedded feasible to use embedded style in this style in small instance. Ho e"er, in any professional site A"oid in professional practice. "ersus large or app de"elopment, a"oid using embedded Web sites style, for it, li!e inline style, can contribute to confusion hen debugging. As ith inline styles, if you#re trying to $hough not ideal, embedded style can be isolate hy a gi"en style isn#t applying, you used to debug and find conflicts in the case Embedded can use embedded style to or! through of multiple style sheets. Wor!flo style for some conflicts. Another use that , find ad"antages as described can be useful, the debugging and helpful is that during de"elopment, , li!e to one ca"eat in all instances of professional or!flo or! in one document, embedding my sites- .emo"e your embedded styles out to purposes styles and building out the content and appropriate e(ternal styles after you#re done mar!up all in the same place. or!ing, test, and you#re good to go. Embedded Where is that styleL What if you ant to A"oid publishing embedded style sheets. style as use it again more efficientlyL &'uic!& fi(es Scenario

Scenario Issues 4a!a laziness5 !able ,# Best 0ractices- Embedded Style %in0ed 1External Style2

-est Practice

%in!ed style is the true &holy grail& of style sheet types. ,t pro"ides us ith the broadest application of styleD allo s us to manage the presentational aspects of a site from a handful of style sheetsD performance is faster due to the bro ser placing the styles into memory 4cache5D and the orst of conflicts are a"oided. %in!ed style sheets are separate te(t documents containing your style rules, sa"ed ith a .css file e(tension and lin!ed to from the H$M% documents you ant to style using the lin! element in the head portion of your mar!up document<head> <lin. rel="st%lesheet" t%+e="teDt/css" src="/sites/all/mod*les/dzone/assets/refcardz/"1E/st%le/ ,lo-al)css"> </head>

,n almost all cases, the lin!ed style sheet is the one you ill be or!ing ith most. Be careful ith case matching bet een your CSS and H$M% documents. ,f you create a selector H8 in upper case, then it ill only select h8s in upper case ithin the mar!up documents. Best practices suggest !eeping all H$M% elements and attribute names in lo er case 4this is re'uired in MH$M%5 and !eeping CSS lo er case as ell, helping to a"oid potential case7related conflicts. Also, hile many programmers find camel case 4classN&Module$ o&5 intuiti"e, this also can cause casematching problems, particularly in larger7scale sites, particularly those being managed by multi7person teams.

lication 3ierarc(y and Sort 4rder

1f course, most or!ing Web de"elopers and designers are ell a are that or!ing ith CSS *ust can#t be that straight for ard+ $here are many reasons hy CSS is as broad in scope as it is, but fle(ibility and po er are t o of the most credible reasons for hy you can approach a gi"en problem ith numerous solutions. With freedom comes responsibility, and the same is true for professional Web de"elopment. ,n order to "isualize hy CSS can 'uic!ly fall from po erful friend to chaotic foe, consider /igure O.

$igure 5# ,magine a global style for the 3ni"ersity itself. $hen, each indi"idual department ants its o n identity. $his is a "ery common large7organization issue, and one hich ine"itably leads to

multiple styles all o"er the site, poorly documented and managed hen in fact some intelligent coordination could be used to manage the site#s presentation much more efficiently.

!(e Cascade
.e"isiting the bro ser, user, author relationship, e can ta!e a loo! at ho rules &cascade& from one style sheet type to another. Here#s the general rule of thumb All e(plicit styles o"erride bro ser style A user style sheet, hen properly authored, ill o"erride author style An inline style o"errides a conflicting embedded style An embedded style o"errides a conflicting lin!ed style

Rule 4rder
$he order in hich rules are sorted becomes critical in resol"ing conflicting rules. Many readers are li!ely to ha"e heard &the rule closest to the content ins&, hich is some hat accurate but also a bit misleading. Sort order, the term that is used to describe the sorting of multiple CSS rules, is the process by hich a Web bro ser sorts the rules it is gi"en. ,f e ha"e a scenario here there are t o lin!ed style sheets, an embedded sheet in the document in 'uestion, and an inline style, the bro ser has to sort through those and resol"e sort conflicts. Consider this MH$M% <!4562789 html 8:;<=6 --//W>6//424 ?H2@< 1)" Atrict//9B"htt+ //333)3>)or,/2C/Dhtml1/424/Dhtml1-strict)dtd"> <html Dmlns="htt+ //333/3>/or,/2C/Dhtml1"> <head> <lin. rel="st%lesheet" t%+e="teDt/css" src="/sites/all/mod*les/dzone/assets/refcardz/"1E/st%le/,lo-al)css" /> <lin. rel="st%lesheet" t%+e="teDt/css" src="/sites/all/mod*les/dzone/assets/refcardz/"1E/st%le/local)css" /> <st%le t%+e="teDt/css"> + {font-famil% 2imes$& </st%le> </head> <-od%> <+ st%le="font-famil% Arial$">Which font 3ill this -eF</+> <+>What a-o*t this +ara,ra+hF</+> </-od%> </html>

,f you imagine all the rules ithin global.css e(panding out, then the local.css e(panding out, then the embedded style added onto that, you get one long style sheet. ,f some here in the first t o , had conflicting rules that styled paragraphs using the Pene"a font, the sort order process ill see the last style in that long sheet as $imes. $herefore, $imes ill be used in all instances of p as defined ithin our scope ith the e(ception of the element containing the inline style. As mentioned earlier, inline styles are more specific, and therefore ill al ays &trump& another style in a scenario li!e this.

S ecificity
$here is one final deal7brea!er for the rules of Cascade and sort, and that is the specificity of a gi"en selector. ,#"e !ept the e(amples here simple for a reason as selectors are complicated and actually ta!e

up about a third of the Core CSS series. Specificity is an algorithm ith a broad base that allo s an author to create "ery specific rules. $hese rules often in"ol"e a number of selector types, and are calculated based on the selectors in use in the rule. ,f a rule is found to be more specific than one that comes later in the sort order the more specific rule is applied no matter here the rule resides in the sort. Consider the follo ing rule(content + {font-famil% Garamond$&

$his is a combination of an ,2 selector 4Fcontent5 and an element selector 4p5. $he space bet een the t o selectors indicates a descendent. So, let#s say , ha"e this rule in global.css. Because it is more specific, any paragraph that descends from an element ith an ,2 of Fcontent ill no be in Paramond, not in $imes. Specificity is one of the terribly misunderstood and undertaught portions of conflict resolution ithin a CSS application hierarchy. 3nderstanding ho to calculate specificity is easier if you ha"e a table a"ailable to or! through a gi"en conflict, then count up the types of selectors that e(ist in your rules in the e(act order sho n in $able :. Exam le Count 6 of ID SelectorsCount 6 of Class SelectorsCount 6 of Element Selectors ul =, =, 8 Fcontent ul li 8, =, < Fcontent ul li ul li8, =, ? !able /# Calculating Specificity We can no see that the most specific rule is the last one. $herefore, any list item style that is not as specific ill not apply to a nested list item ithin the document area ith an ,2 of &content&, regardless of here that more specific rule resides in the sort. $here#s one specific specificity e(ception here. .emember that , mentioned inline style has the highest specificityL $able O sho s ho inline style comes into playPresence of Inline style Count 6 of ID Count 6 of Class Count 6 of Element in element Selectors Selectors Selectors ul 8, =, =, 8 Fcontent ul li 8, 8, =, < Fcontent ul li 8, 8, =, ? ul li !able 5# Specificity and presence of inline style Exam le ,f there are inline styles ithin the element, a count of 8 goes into the first 4optional5 column, s!yroc!eting the specificity of the gi"en element. $his is hy inline style is really so po erful.

$ind More 4nline


$he follo ing online references ill be helpful additions to the learning in this refcard. Reference UR% CSS <.8 Specification http-GG . >.orgG$.GCSS<8G CSS 2iscussion %ist http-GG .css7discuss.orgG CSS72 Wi!i 4%ots of helpful information and lin!s5http-GGcss7discuss.incutio.comG CSS Qen Parden 4Beautiful sho case site5 http-GG .csszengarden.comG

!able 7# 1nline .eferences

8ext Ste s
,t should be clear that CSS has nuances that only time and e(perience can re"eal. Well, that and good references+ %oo! for the remaining &Core CSS& series and go into depth ith selectors, the bo( model, floats, positioning and the z7inde(. Sound e(citingL , thin! so too+

Core CSS: Part II


By Molly E. Holzschlag

All about Selectors


Eust in case you#"e not read Core CSS- 0art ,, ,#ll briefly re"ie the purpose of a CSS selector. A selector in a style sheet signals the bro ser to find matches ithin those mar!up 4H$M%, MH$M%, MM%5 documents to hich the style sheet is related. $here are more than a fe selectors a"ailable for use 4$able 85, but e"en intermediate and ad"anced CSS authors don#t al ays ha"e an opportunity to use some of them, largely due to crossbro ser support issues for a gi"en selector. Core CSS- 0art ,, ill co"er CSS <.=G<.8 selectors. Where a selector is una"ailable in contemporary Web bro sers, a caution ill be pro"ided to alert you to any support concerns. Version Date Element Selects by matching element Class Selects by matching class name ,2 Selects by matching id name 0seudo Class Selects by matching predefined pseudo class 2escendent 4also !no n as &conte(tual&5 Selects by descendant elements Child Selects by first7le"el 4child5 elements Ad*acent Sibling Selects by matching sibling element Attribute Selects by matching attribute names and "alues 0seudo Elements Selects by matching predefined pseudo element !able "# CSS Selectors Co"ered in this .efcard $o assist in "isualizing ho these selectors actually match, for each e(ample you#ll see an element, the corresponding CSS, and a document tree that "isualizes hat is selected ithin a sample document. Also pro"ided are some use e(amples.

$here#s also a uni"ersal selector, R, hich hen used ill select e"ery single element ithin a document. ,t#s used in se"eral hac!s, including the infamous &star html& hac!, hich is problematic and in"alid. While the uni"ersal selector is important to !no about, it#s probably not going to be something you use too often in real7 orld scenarios.

Element Selectors
Element selectors, also referred to as &type& selectors, select by matching elements. $hey are "ery broad in scope. /or e(ample, if , ha"e a million documents ith many more millions of hH elements ithin them, by using an element selector , can single handedly apply styles to all of those hH elements using one rule. Element selectors are supported in all CSS bro sers and are "ery idely used for these reasons. Here#s a CSS rule using an element selectorhH {color (f""$ font-famil% Garamond$ font-size HH+D$ font-variant small-ca+s$&

,n the corresponding mar!up document4s5, all h<s are selected and the style is applied 4/igure 85.

$igure "# An H$M% document tree sho ing that each of the h<s in the document has been selected.

Class Selectors
Class selectors are e(tremely useful selectors that allo authors to add a class attribute to a gi"en element in the mar!up, ith a custom "alue. $hen using that "alue preceded by a dot, rite a corresponding rule using the class name. An e(ample of an element ith an added class attribute in the mar!up document ould be<+ class="3arnin,">An% +ara,ra+h in an% doc*ment on an% +a,e containin, this class 3ill have the class r*les a++l%)</+>

,n the CSS)3arnin, {color red$ font-3ei,ht -old$&

/igure < sho s ho this class, as ritten, ill apply to both elements ith the class attribute named & arning&.

$igure )# Selecting all elements ith a class of arning.

)ou can limit a class to a specific element by placing the element selector before the class- p. arning. ,f you ere to do this, only the paragraph ill ta!e on the class styles. Any other, non7conflicting styles that e(ist for the element p ill also be sorted and included. Multi9Classing An interesting and occasionally useful techni'ue is multi7classing. $his means using more than one class to get the style you#re after. A good use scenario ould be a portal site in hich you ha"e multiple modules that ha"e common colors and features, but re'uire different bac!ground images. Consider the follo ing style rules)mod*le1 {3idth H""+D$ mar,in 5+D$ -order 1+D solid -l*e$& )3eather {-ac.,ro*nd-ima,e *rl/ima,es/Is*nshine)0+,I1$&

$o multiclass, ,#d simply add both classes to the module element, ith each name separated by a space<div class="mod*le1 3eather"> ) ) ) </div>

$he element ill no pic! up the styles of both classes. $ypically, use of <7> class names can be helpful ithin conte(t, but it#s not a practice ,#d recommend using ithout a strong sense of your site hierarchy and management. ,t#s also important to point out that the source order of the class names in the mar!up document is of no conse'uence. Ho e"er, if there are conflicts bet een the classes, sort order and specificity rules in CSS ill calculate hich rule ta!es precedence.

A"oid underscores and other special characters in class and ,2 names. $he best practice currently is to use hyphenation- na"7main 4not na"Smain5. Also, hile camelCasing is e(tremely useful to coders, it can add a layer of e(tra testing because CSS re'uires case7matching, so case ithin the mar!up documents and any associated CSS must match for rules to apply.

ID Selectors
,2 selectors are meant to identify a discrete portion of a document. $his means an ,2 name can be used e(actly one time in a gi"en document. $his is hy ,2#s are particularly useful in CSS layout hen identifying significant portions of the document, such as &content& &na"& or &site7info&,because they are uni'ue, discrete pieces of the document structure. Assuming only one document, here#s a rightG rong comparisonRig(t:
<div id="content"> ) ) ) </div> <div id="s*--content"> ) ) ) </div>

:rong:
<div id="content"> ) ) ) </div> <div id="content"> ) ) ) </div>

,n the style sheet ,2 selectors are ritten using the hash &F& 4also !no n as an &octothorpe& for the ord gee!s among you5 preceding a custom name.
(content {3idth 5""+D$ -order 1+D solid (fff$&

/igure > sho s ho this ill no select the di" ith the uni'ue id attribute named &content&.

$igure *# 3sing ,2 selectors to identify the content area. $he id name can only be used once per document, but many times ithin a site.

While ,2 and Class names are in fact customized to suit your needs, it#s considered best practice to a"oid presentational names such as .redfont or (side-ar. What happens hen the boss says &update all the red fonts on the site to be blueL& Easy enough to change the style in moments and update all those fonts, but no the mar!up documents are littered ith class="redfont" hen the actual "isual result is blue+ $o a"oid confusion of this nature, use naming that is descripti"e 4referred to as semantic naming5 and here possible, consider creating con"entions to be used site7 ide.

Pseudo Class Selectors


A pseudo class selector is a set of predefined class7li!e selectors. 0seudo class selectors are ritten

ith a colon follo ed by the predefined pseudo class name. 0seudo classes can then be attached to a "ariety of elements in order to achie"e a gi"en result. ,t#s li!ely you#"e used pseudo classes as much as element, ,2, and class selectors, for a number of them are integral to styling lin!s 4$able <5. Selector Pur ose -lin! Selects lin!s that ha"e not been "isited -"isited Selects lin!s that ha"e been "isited Selects an element as the mouse passes -ho"er o"er. -focus Selects the element that has focus -acti"e Selects a lin! that is being acti"ated -first7child Selects an element#s first child -lang Selects by matching human language !able )# 0seudo Class Selectors Exam le a-lin! Hcolor- blueDI a-"isited 4color- "ioletDI a-ho"er Hcolor- FcccDI a-focus Hbac!ground7color- orangeDI a-acti"e Hcolor- redDI di"-first7child Hfont7style- italicDI html-lang 4de5 Hfont7size- ;=JDI

@ote that hover, foc*s and active are all referred to as &dynamic pseudo classes& because along ith presentation they also allo for dynamic beha"ior, such as creating interesting loo!s for na"igation, assisting ith usability, and styling form controls. An e(ample ould be 4/igure ?5.

$igure +# $he form control that has focus 4in this case the te(t input bo( associated ith &@ame&5 ta!es on the style you see here using the foc*s selector on the input element.

C(ild Selectors
Child selectors are created by combining a parent element ith the T combinator and a child element. $his allo s you to style only the child element or elements of the parent, ithout ha"ing those styles inherit do n the tree. ,t#s also a great ay to reduce the use of class attributes, hich help ma!e managing sites all the more easy. Consider /igure K.

$igure ,# An unordered list element 4parent5 ith three list item child elements. Here, e ha"e a parent element, ul, and e ant to style each of the three list items belo . $he CSS rule ould simply be*l>li {-order "$ mar,in "$ +addin, "$&

@o all the children of any ul ill ha"e = border, margin and padding. Because in this e(ample, the *l has an ,2, e can use that to limit this rule only to that discrete document element*l(nav > li {-order "$ mar,in "$ +addin, "$&

@ot only has this limited the rule to the ul ith an id of &na"&, but it has also made the rule more specific both literally and technically. Also, you#ll note that there#s no hite space surrounding the

combinator in the first e(ample, hereas in the second, there is. Either ay is acceptable according to the spec. )ou can use as many children ithin the selector as is re'uired. ,n a scenario such as /igure :, you could rite a "ery specific selector to select only the children of the nested ordered list item and style it ith a leading zero decimal.

$igure /# $ree depicting a nested ordered list ithin a nested unordered list ith a parent unordered list. 3sing Child selectors, e can select children by follo ing their ancestral path. $he resulting CSS ould be*l(nav > li > *l > li > ol > li {list-st%le-t%+e decimal-leadin,-zero$&

CAU!I48: C3I%D SE%EC!4RS ARE 84! IMP%EME8!ED I8 I8!ER8E! E;P%4RER /#< 4R -E%4:#

Descendent Selectors
2escendent selectors, as ith Child selectors, begin ith an element that has descendents. $he combinator for descendents is a space. Since children are descendents, e can re7e(amine the same parent7child relationship e first did hen e(amining child selectors 4/igure O5.

$igure 5# Children are also descendents. ,f , anted to set a style for any descendent list items ithin an unordered list using a descendent selector, , can do so as follo s*l(nav li {list-st%le-t%+e none$&

$he differences is that not only the li children of the *l ill be styled, but all li descendants of that *l and the ol ill get the same style as ell since all list items descend from the original unordered list 4/igure ;5.

$igure 7# 2escendent selectors select all descendents of the defined parent element, in this case, nested unordered lists. @ote that the list item that is child to the ordered list element ill also recei"e the style, for it too is a descendent of the original parent list. As ith child selectors, e can create strings to reach a particular element ithin the tree*l(nav li *l li ol li {list-st%le-t%+e zero$& decimalleadin,-

$he selector ill no select the "ery last list item in /igure ;, hich is the child of the ordered list item element in the tree hierarchy. @one of the other list items ill ta!e on this rule. /ortunately, 2escendent selectors are idely supported in current CSS bro sers including ,E :.= and later.

Ad=acent Sibling Selectors


An Ad*acent Sibling selector allo s you to select an element based on its nearest sibling element. Consider the follo ing mar!up<div> <h1>@ain 6ontent Header</h1> <+>Jirst +ara,ra+h</+> <+>Aecond +ara,ra+h</+> <+>2hird +ara,ra+h</+> </div>

,t#s a common design theme to style a first paragraph some hat differently using a larger font, or emphasized font, bringing the reader#s eye to the critical introductory material. 3sing an Ad*acent sibling selector, e can do this 'uite easily ithout using a class attribute on the first paragraph. $he combinator for the Ad*acent sibling selector is the plus sign, C.
h1K+ {font-3ei,ht -old$&

$his selects the first ad*acent paragraph element 4/igure 95, ith no change to any of the other siblings.

$igure ># Selecting a sibling using Ad*acent sibling selectors.

)ou can use multiple sibling elements to reach a gi"en sibling. %et#s say you anted to select not the first but the third paragraph in the e(ample and ha"e it display as italic. $he synta( ould beh1K+K+K+ {font-st%le italic$&

/igure 8= sho s the selection.

$igure "<# Selecting a further remo"ed sibling using a string of ad*acent siblings. CAU!I48: AD?ACE8! SI-%I8' SE%EC!4RS ARE 84! IMP%EME8!ED I8 I8!ER8E! E;P%4RER /#< 4R -E%4:#

Attribute Selectors
Attribute selectors are a curious piece of selectors because they really are more a!in to programmatic pattern matching than presentational design needs. $here are four Attribute selectors that are a"ailable in CSS <.8 4$able >5. Attribute Selector UnameV Pattern Matc(ing Exam le aUtitleV Hfont7style- italicDI imgUsrcN#GsitesGallGmodulesGdzoneGa ssetsGrefcardzG=<KGphoto.*pg#V imgUaltWN&0ortland&V aUtitleXN&top7do n&V

Selects by presence of attribute name for a gi"en element Selects by presence of the attribute name plus its UnameC"alueV "alue Selects by the attribute name plus the presence of a UnameWN&"alu specific space separated ord ithin the attribute e&V "alue UnameX Selects by the attribute name plus the presence of a N&"alue&V hyphenated ord ithin the attribute "alue !able *# Attribute Selectors !o select by attribute name### Compare the follo ing t o lin!s<a href=htt+ //moll%)com/" title=",o to @oll%Is Wesite">@oll%)6om, =nc)</a> <a href="htt+ //moll%)com/">@oll%)6om, =nc)</a>

,n the first lin!, there#s a title attribute. 3sing the follo ing CSSaLtitleM {font-st%le italic$&

We can style any anchor elements ith a title attribute present, but the style ill not apply here no title attribute is present 4/igure 885.

$igure ""# Applying style using an attribute name selector. !o select by attribute name and &alue### Consider the follo ing t o H$M% image elements<im, src=I/sites/all/mod*les/dzone/assets/refcardz/"H5/ima,es/+hoto)0+,I> <im, src=I/sites/all/mod*les/dzone/assets/refcardz/"H5/ima,es/screenshot)0+,I>

$o add a specific style to the first instance, you can use the follo ing synta(imgUsrcN#GsitesGallGmodulesGdzoneGassetsGrefcardzG=<KGphoto.*pg#V Hborder- <p( solid F===DI $he selector ill match only an image element ith an attribute of src=I/sites/all/mod*les/dzone/assets/refcardz/"H5/ima,es/+hoto)0+,I and no other image elements ill be selected 4/igure 8<5.

$igure ")# Applying a border to only the photo using the complete 4nameC"alue5 attribute selector. !o select by resence of multi le s ace se arators and (y (ens### Consider the follo ing MH$M% image elements<im, src=I/sites/all/mod*les/dzone/assets/refcardz/"H5/ima,es/vacation"1)0+,I alt="8ortland vacation +hoto" /> <im, src="/sites/all/mod*les/dzone/assets/refcardz/"H5/ima,es/vacation"N)0+," alt="vacation +hoto" /> <im, src="/sites/all/mod*les/dzone/assets/refcardz/"H5/ima,es/vaction">)0+," alt="vacation +hoto of 8ortland" />

$o add style to only those images that ha"e an alt attribute 4and all your images should+5, and a series of space separated ords that include &0ortland& 4note that the case must match as ell5 you#d use the

follo ing synta(im,LaltO="8ortland"M {-order 5+D solid ,reen$&

/igure 8> sho s the results.

$igure "*# Applying a border to only the photos ith multiple space separated ords here &0ortland& appears ithin the image#s alternati"e te(t string. Similarly, you can select by the presence of an attribute name plus a hyphenated, specified ord ithin the "alue. Consider the follo ing H$M%<+ title="n*rser%-rh%me">@ar%, @ar%, P*ite contrar%, ho3 does %o*r ,arden ,ro3F</+> <+ title="son,-l%ric">And sheIs -*%in, a Atair3a% to Heaven</+> <+ title="traditional-rh%me">Coses are red, violets are -l*e</+>

Add this CSS rule+Ltitle="rh%me"M {color -l*e$&Q

Both the first and third elements ill ta!e the style, hereas the middle one ill not. 4/igure 8?5.

$igure "+# Applying style using pattern matching. @ote ho e"er that in the case of hyphen matching, order matters. $he hyphenated ord must be first in the string. Had e s itched the third paragraph#s attribute to title="rh%me-traditional" the style should not apply. CAU!I48: A!!RI-U!E SE%EC!4RS ARE 84! IMP%EME8!ED I8 I8!ER8E! E;P%4RER /#< 4R -E%4:#

Pseudo Elements
As ith pseudo classes, pseudo elements are predefined elements ithin CSS. $here are four of hich to be a are, as described in $able ?. Pseudo Element -first7line Pur ose Selects only the first line of te(t in a gi"en element. Exam le bloc!'uote-first7line Hfont7 eightboldDI

Pseudo Element -first7letter

Pur ose

Exam le

Selects only the first letter of te(t in a gi"en p-first7letter Hfont7size- <K=JI element 3sed to generate content before a gi"en -before '-before Hcontent- open7'uoteDI element -after 3sed to generate content after a gi"en element '-after Hcontent- close7'uoteI !able +# 0seudo Elements in CSS <.8 $irst line and letter seudo elements Both the -first7line and -first7letter pseudo elements are typically used to add typographic features to a gi"en set of te(t. $he follo ing H$M% bloc! sho s hat happens in the document<+><etIs -e honest) We all ma.e mista.es) Aometimes 3e can -e too hard on o*rselves, or others, for those mista.es) =t ma.es me remem-er that lon, a,o and far a3a%, someone ver% 3ise said </+> <-loc.P*ote>2o err is h*man, to for,ive divine)</ -loc.P*ote> <+>Havin, -oth the ca+acit% to -e for,ivin, of others and the a-ilit% to for,ive %o*rself is +art of learnin, ho3 to -e 3ise)</+>

3sing the decorati"e pseudo elements, here are the CSS e(amples from $able ?-loc.P*ote first-letter {font-size + first-line {font-3ei,ht -old$& H5"#&

/igure 8K sho s the results.

$igure ",# 3sing first letter and line pseudo elements to apply style. @otice that in the case of -first7 line, the &line& is defined as hate"er amount of characters ma!e up the first line. Because this is not al ays the desired result, using min-3idth and maD-3idth properties to limit line length here"er possible can address this issue. Both the first letter and line pseudo elements ha"e good support across bro sers, including ,E :.=. 'enerated Content A fascinating if contro"ersial portion of CSS is called generated content. $his is hen, using the pseudo elements -before andGor -after, you as the author can actually generate te(t, symbols and images. What#s more, you can style them on the page. Consider the 'uote from earlier-

<-loc.P*ote>2o err is h*man, to for,ive divine)</ -loc.P*ote>

@o , let#s generate 'uote mar!s and style them using CSS-loc.P*ote -loc.P*ote font-size -loc.P*ote font-size {font-size >"+D$ font-3ei,ht -old$& -efore {content o+en-P*ote$ color red$ 1H"+D$& after {content close-P*ote$ color red$ 1H"+D$&

/igure 8: sho s the results in /irefo(.

$igure "/# 3sing pseudo elements to generate and style the 'uote mar!s. $he ca"eat, and the cause of misuse and therefore contro"ersy has to do ith the fact that the content generated by pseudo elements results in pseudo content. ,n practical terms, this means the content ne"er actually appears in the content layer, only the presentational layer+ ,n a situation here the generated content is largely decorati"e or practical in some sense but does not inhibit access to important data, this is fine. $a!e a loo! at the generated source by /irefo( and you#ll see the 'uotes called for do not appear in the code at all. But hat if e ere to generate the message itselfL ,n the H$M%<-loc.P*ote></-loc.P*ote>

And in the CSS-loc.P*ote after {content for,ive divine" font-size "2o err is h*man, to E"+D$&

/igure 8O sho s the generated results.

$igure "5# )ou can generate actual content, but it ill only appear on the presentational surface. Ho e"er, hen e loo! at the source code, e see that the generated content does not appear ithin the code 4/igure 8;5.

$igure "7# While e can "isually see the generated content on the screen, it does not appear ithin the actual body of the document. $herefore, if you are generating important content to the des!top screen that must be comprehensible, generated content is not the ay to go. ,t can cause problems for copying, printing, reading, sa"ing, and for anyone using ,nternet E(plorer ,EO or earlier, simply non7e(istent due to complete lac! of implementation for the -efore and after pseudo elements.

Combining Selectors
Selectors can be combined, gi"ing authors highly specific ays of or!ing to style and manage documents.

'rou ing
Selector grouping is simply placing a number of selectors that all share common properties separated by commash1, hH, h>, hN, h5, hR, +, P, -loc.P*ote, td, (content, )standard {color ("""$ mar,in 5+D$&

@o all these selectors ill share the declaration properties.

Prouping is useful hen you ha"e a lot of shared features bet een elements. )ou can group those elements as sho n, and then create more specific rules for indi"idual elements. )ou might ha"e heard of &CSS reset& or &normalization& hich uses this techni'ue.

Combining Selector !y es
As you#"e already seen in se"eral of this refcard#s e(amples, you can combine selector types in order to create hat some designers and de"elopers refer to as comple( selectors. $able K sho s some e(amples as ell as the selectors definition,and to help you practice,the selector#s specificity. .ead selectors from

the right of the selector,it helps+ Combined Selector Meaning S ecificity 1CSS )2

Selects child paragraphs descending from a element that has a class of &module& and is ithin the Fcontent di".module T p 8,8,< uni'uely identified portion of the document that is identified as &content& 8,=,? 4CSS <5 Fmain7na" ul li ol T li-ho"er Selects only the first letter of te(t in a gi"en element 8,8,? 4CSS <.85 Any table element that is a child of a table data tr T tdCtdCtd T table element that is the third sibling from a table ro =,=,K element. Fcontent ul T li C li Any anchor ith an href of http-GG molly.comG that is ahrefN&GsitesGallGmodulesGdzoneGathe second child sibling from an unordered list 8,=,? 4CSS <5 ssetsGrefcardzG=<KGhttp-GGmolly. element descending from an element ith an ,2 of 8,8,? 4CSS <.85 comG&V content. !able ,# Combining selectors to create highly specific rules

Resources
$he resources in $able : should help you get more information on the topics discussed in this card. UR% Reference http-GG . >.orgG$.GCSS<8Gcascade.htmlFspeci Specificity in CSS <.8 e(plained ficity http-GG . >.orgG$.G.EC7 Specificity in CSS <.= CSS<Gcascade.htmlFspecificity Select1racle- /ree online tool to help you calculate http-GGgallery.theopalgroup.comGselectoracleG selector specificity http-GGde"eloper.yahoo.comGyuiGresetG )ahoo+ 3ser ,nterface library reset http-GGmeyer eb.comGericGthoughtsG<==OG=KG=8Gres Eric Meyer#s ta!e on using reset or &normalization& et7reloadedG !able /# .esources

Core CSS: Part III


By Molly E. Holzschlag

A-4U! !3IS RE$CARD


$o understand and manage attracti"e design and layouts, gaining an appreciation for the ho to manage the CSS Bo( Model, /loats and 0ositioning is paramount. ,n this third and final refcard in the Core CSS series e turn our attention to the "isual models that e(ist ithin CSS. )ouYll learn not only about ho "isual models or!, but ho to troubleshoot and repair common problems too.

!3E CSS VISUA% M4DE%


$he path to master todayYs options for layout re'uires a significant study of the ay that bro sers or! ith the mar!up and style theyYre interpreting. Current Web bro sers implement hat is !no n as the ZCSS Bisual Model[ and lay out content based on a foundation of lines and bo(es.

%ines and -oxes


,tYs "ery li!ely youY"e heard the terms Zinline[ and Zbloc![ to describe H$M% and MH$M% elements. ,Yll re"ie their meaning here in the conte(t of the model. An inline element by default is one that lies on the line ith no subse'uent brea!, unless the line has come to the end of a"ailable bro ser space in hich to flo . Bo(es that fall on a line in this fashion are called line bo(es 4/igure 85.

$igure "# ,magine this is a series of te(t ithin a paragraph. @ote ho the inline elements do not cause a line brea!, and that they generate hat is !no n as a Zline bo(.[

A bloc! le"el element by default defines a bloc!, and there is a brea! bet een it and the ne(t element.

$igure ). ,Y"e ta!en the original te(t and placed it ithin a paragraph element. $hen, duplicated the element belo , gi"ing us t o bloc! bo(es each containing inline bo(es.

!(e CSS )#" Visual Model@ continued


$he most critical piece to understand is that e&ery element creates a box. $his bo( is the foundation for hat is !no n as the bo( model and is a critical component to understanding ho to style elements ithin your document.

!3E -4; M4DE%


E"ery element bo( can be styled by the bo( components. ,n CSS <.8, the Bo( Model consists of the content at center, and the top, right, bottom and left borders, padding and margin. $he borders, padding and margin "alues for each or any side of the bo( are all optional and can be styled using CSS. Bo(es only go to the idth andGor height of their content. )ou can control the idth of bloc! bo(es by pro"iding a specified idth, but in the case of floats, youYll need to use clearing and other techni'ues to Zstretch[ element heights.

$igure *. $he CSS Bo( Model.

,tYs important to point out that because of flo issues ithin a bro ser, inline elements canYt ta!e a idth. $herefore, hile you can style other elements of an inline bo(, you canYt set an e(plicit idth.

!(e -ox Model@ continued


3nderstanding the bo( model is critical because it gi"es designers a greater sense of hat they can actually style. /or e(ample, you can add bac!grounds or styled borders to the content surrounded by the bo(. A bit of a arning, though, the Bo( Model in ,E: and belo does not follo the CSS bo( model. $herefore, it is necessary to use the correct 21C$)0E declaration 4See Core CSS- 0art , .efcard5 in ,E: and ,EO to ensure the proper bo( model is in use. 1ther ise, idth measurements ill be significantly different. Margin bac!grounds in bo(es are transparent.

About 8ormal $lo.


@ormal flo at its most simplistic is simply the default flo of elements ithin a document. Here is an e(ample of normal bro ser flo hen e diminish the idth of the bro ser, content ill flo do n and to the left 4/igures ?7:5. ,f e re"erse the sizing and e(pand the bro ser, the content ill flo up and to the right 4simply re"erse "ie ing order of /igures ?7:5.

/igure ?. A paragraph in the normal flo .

$igure ,# As the bro ser indo is resized, te(t flo s do n and to the left. @otice the appearance of a scrollbar.

$igure /# As e continue to ma!e the bro ser indo smaller, the paragraph reflo s to fit the a"ailable idth, hile the te(t flo s to the left in a do n ard manner, elongating the page.

A great ay to gain an appreciation of normal flo is to simply create an H$M% page ith multiple paragraphs of te(t, and then size and resize the bro ser, atching ho the flo beha"es.

!3E P4:ER A8D PR4-%EM 4$ $%4A!S


/loats ha"e become a "ery critical part of todayYs CSS approach to "isual layout. At first glance, the concept is "ery simple. While floating elements can assist us in doing all !inds of "isual magic,there are challenges inherent to using them, including the ay they are rendered in bro sers.

!(e -asic Intention of $loats


,nterestingly, floats ere not really en"isioned as a means for creating columns, although thatYs often ho e use them. .ather, they ere de"eloped to allo te(t to flo around another element hich has been set to the left or the right, such as an image. $his is something e see a great deal in design, as you can see in /igure O.

$igure 5# /loating allo s for te(t to flo around a floated bo(. ,n this case, the image is floated right, and the te(t flo s

around the image.

$he more e use floats for layout, the more challenged e are to find ays of controlling and brea!ing the manipulation of flo . /loated elements are shifted to the left or right of the normal flo . ,n the case of /igure ;, the image element is shifted to the left and therefore the te(t flo s to the right.

$igure 7#,f the image is floated left, the te(t flo s to the right.

,tYs important to note that the mar!up stays the same\itYs only the CSS that changes. An e(ample of the mar!up ould be<hH>;arrel 6act*s<</hH> <im, src=S--cact*s)0+,S alt=S+hoto of -loomin, -arrel cact*sS /> <+>2he colors are -ea*tif*l, -*t the -arrel cact*s has an inner secret if %o* are in need of h%dration in the desert, this cact*s has a lot of fl*id inside and has saved the lives of man%)

$he CSS "alues ill of be different in terms of manipulating the location of the image and the te(t flo , in the first case, the image is floated right, and in the second, left. 1ther elements ill simply flo around the floated element once a float has been applied.

!(e Po.er and Problem of $loats@ continued $loat -e(a&ior


3nderstanding ho floats beha"e 4or donYt5 ithin a bro ser en"ironment is critical to troubleshooting a "ariety of issues, particularly hen it comes to layout. While floats can be your best layout friend in many, many situations, !no ing ho floats beha"e in general ill gi"e you the upper hand+ $he first thing to !no is that floats are not in the normal flo . $his means that other te(t and elements ill continue to flo around the floated elements. ,n /igure 9, e see hat happens if t o elements are floated to the right and left. ,f not contained by another element that has an e(plicit idth, the floated elements ill continue to spread apart as the bro ser size increases, and come together as the bro ser size decreases.

$igure ># 1ne bo( floated left, another right. ,f not contained, these bo(es ill continue to spread apart or get closer as the bro ser is resized.

,f youY"e e"er had te(t begin to unintentionally cra l up around the side of a floated bo(, the solution is float clearing 4see ZClearing /loats[ later in this reference5. ,n order to get floats to stac! up nicely ne(t to one another and a"oid this beha"ior, e simply float them all in the same direction, typically left 4/igure 8=5.

$igure "<# ,f e float elements in the same direction, theyYll line up ne(t to each other. $his is one ay of creating columnar designs.

What happens if thereYs not enough room ithin the bro ser 4or the set idth of a container element5L $he subse'uent floated element Zfalls off[ the line and see!s the first a"ailable space 4/igure 885.

$igure ""# ,f an element cannot fit into the a"ailable space, the bo( ill Zfall off[ the line and mo"e to the first a"ailable space in the flo .

$loat -e(a&ior@ continued

,E: ill drop the float do n in if there is no space, incongruent ith other bro sers. ,f youYre de"eloping in a /irefo( en"ironment, be sure to test constantly in ,E as ell. $his issue, referred to as Ztolerance[ can be remedied by modifying idths slightly to accommodate ,E. /loats can be contained by setting e(plicit idths on containing elements, and on the floated bo(es themsel"es. $his doesnYt eradicate tolerance problems, but it gi"es you a more finite idea of ho to mathematically arrange your elements 4/igure 8<5.

$igure ")# By containing elements and gi"ing them a idth, e can begin to create columns.

By containing elements, e can create conte(ts for interface components. ,f , anted to create three columns as abo"e, , could create three di"s ith specific idths, borders, padding and margins for each of the columns, and then set that ithin another di", hich , ould gi"e an e(plicit idth too, containing the three indi"idual columns-

lt div> lt div>col*mn 1 lt /div> lt div>col*mn H lt /div> lt div>col*mn > lt /div>

lt /div>

1f course, using di"s for e"erything is o"er!ill, because many H$M% elements actually ha"e this sort of mechanism built right in+ Consider an unordered list ith three list itemslt *l> lt li>col*mn 1lt /li> lt li>col*mn Hlt /li> lt li>col*mn >lt /li>

lt /*l>

As you can see, the is an element, and therefore creates a bo(. We can then style that bo( as a container for the list items residing ithin. ,f thereYs a logical reason to use a list, such as ith na"igation, or lin!ed interface components, consider using semantic elements instead. $his is called minimal mar!up and is an e(tremely helpful techni'ue.

$hereYs no such thing as Zdi"[ based design. $hat term is popular but highly inaccurate. ,n CSS, itYs not that e use di"s to create bo(es, but that the element bo(es are already there. 3se di"s only here necessary for containment and structure.

!(e Po.er and Problem of $loats@ continued Clearing $loats


So hat happens hen you ant to stop the flo of te(t, or a floated bo(, and return to the normal flo L )ou ha"e to clear your floats 4/igure 8>5.

$igure "*#Clearing floats is the process of returning the ne(t consecuti"e element to the normal flo .

,n terms of floats for layout, if you ant to be able to ha"e content belo floated elements, such as a traditional Zfooter[ here site information ill go, clearing is necessary. $his allo s the subse'uent elements to return to the normal flo 4/igure 8?5.

$igure "+#1nce the float is properly cleared, e return to the normal flo , hich is ho floated columns.

e can create a footer beneath the

$here are numerous ays to clear floats. A "ery popular one is the creation of a clear class and the use of the property Zclear[ and a "alue of both)clear {clear -oth$&

0eople ill then use a di" or a brea! element to clear the float<div class=SclearS></div> or <-r class=SclearS />

My preference of the t o is the brea! element, as an empty di" is a non7empty element ith nothing inside it. While still slightly presentational, at least Zbrea![ has meaning in this case 4/igures 8K and 8:5.

$igure ",#$he float is properly cleared. @otice ho the column to the left doesnYt fill the entire a"ailable space\this is normal beha"ior. $he important issue is that the bottom7most element is cleared and does not try to Zcreep up[ into the a"ailable space.

$igure "/#E"en hen a tolerance problem forces the far right column off the line, notice that it does not encroach upon the space abo"e it. $his is because itYs not in the normal flo . Also, note that despite the tolerance issue, the bottom7most element remains clear of the floated elements.

CSS P4SI!I48I8'
CSS positioning is a po erful piece of CSS that allo s us to position elements in a "ariety of ays. 1ne of the problems ith positioning is that it has not been ell articulated, particularly relati"e positioning, o"er the years. ,t too! me a long time to understand e(actly hat relati"e positioning really as, or as useful for. $herefore, ,Yll start ith relati"e positioning and or! from there.

Relati&e
.elati"e ,f the fathers of CSS had been thin!ing about naming it a little more carefully relati"e positioning ould be called Zoffset[ positioning. Essentials for relati"e positioning A bo( ith a position- relati"eD designation remains in the normal flo A bo( ith position- relati"eD creates a ne instance of normal flo ithin it .elati"e positioning is most useful for offsetting bo(es or creating a positioning conte(t 4see .elati"ely Absolute later this reference5 ,magine three paragraphs of te(t in the normal flo 4/igure 8O5.3sing CSS ,Y"e hidden the "isibility of the te(t in the second paragraph to ma!e the "isualization of relati"e positioning clearer.

$igure "5#$hree paragraphs in the normal flo .

HereYs some CSS that offsets the paragraph using relati"e positioning-

+ {3idth N""+D$ -order 1+D solid -l*e$& +(rel {+osition relative$ to+ 5"+D$ left 2he offset can -e seen in Ji,*re 1!)

5"+D$&

$igure "7#$he second paragraph, positioned relati"ely.

At this point youYre probably ondering, hat is that paragraph being positioned toL $his is hy , say the term relati"e in this instance is so confusing. $he ans er is not hat youYd e(pect. A relati"ely positioned element is positioned in relation to its location in the normal flo . ,n other ords, the bro ser still Zsees[ the positioned element in the flo but on the design surface, itYs "isually mo"ed from here it ould ha"e been. $his is hy the big space is left behind, almost a ghost of the paragraph. $he bro ser interprets the element as being in the normal flo .

Absolute
Absolute positioning is a little clearer in its terminology, and perhaps a bit more logical in its beha"ior. An absolutely positioned element ,s remo"ed from normal flo ,s positioned in relation to a positioned parent element the root element of H$M% Subse'uent content flo s into the no a"ailable space

CSS Positioning@ continued


HereYs the CSS used to position the bo(+(rel {+osition a-sol*te$ to+ 5"+D$ left 5"+D$&

,f e briefly re"isit normal flo 4/igure 895, e can compare the before and after positioning.

$igure ">#@ormal flo , again.

$igure "># @ormal flo , again.


$igure )<#$he second paragraph, positioned absolutely. @otice ho the element is positioned absolutely from the top, left area 4this can be the H$M% element or another element, such as a di", that is positioned5. $he element is ta!en out of the normal flo , hich is hy the subse'uent paragraph flo s up into the a"ailable space, unli!e relati"e positioning.

$ixed
/i(ed positioning is actually a subset of absolute positioning and can be "ery useful in creating static elements on the design surface hile other elements flo behind.
h1 {3idth 1""#$ +osition fiDed$ to+ "$ left "$ -order 1+D solid (EEE$ -ac.,ro*nd-color (ccc$&

Elements that are fi(ed are done so in relation to the bro ser chrome 4/igure <85.

$igure )"#$he h< gray bo( is fi(ed to the left and top of the bro ser chrome.

As , scroll the bro ser, the bo( remains fi(ed 4/igure <<5.

$igure ))#As , scroll, the te(t flo s under the positioned bo(. $rue to its term, the bo( remains fi(ed.

/i(ed positioning isnYt implemented in ,E:, although ,EO does implement it, as does ,E;. ,f e ere "ie ing this in ,E:, the fi(ed bo( ould simply scroll off *ust as if it ere a non7positioned element.

Creating a Positioning Context: ARelati&ely AbsoluteB


1ne techni'ue that is "ery helpful to designers ho are using a combination of floats and positioning to accomplish their layouts has been coined [.elati"ely Absolute[. Creating a Positioning Context: ARelati&ely AbsoluteB@ continued .emember, a relati"ely positioned bo( creates an instance of normal flo , hile it itself remains in the normal flo of the document. $herefore, creating areas that stay together as a unit can be accomplished by creating a containing element that is relati"ely positioned ithout offset "alues-

*l(s*--nav {+osition relative$ 3idth >5"+D$ +addin, N"+D$ -order 1+D solid -lac.$& = then st%led the list items and lin.s li {list-st%le-t%+e none$& a {teDt-decoration none$& li(home {+osition a-sol*te$ 3idth 1""+D$ left 1"+D$ -order 1+D solid ,reen$& li(+rod*cts {+osition a-sol*te$ 3idth 1""+D$ a-sol*te$ left 1H"+D$ -order 1+D solid red$& li(contact {+osition a-sol*te$ 3idth 1""+D$ left HN"+D$ -order 1+D solid -l*e$&

$his CSS remo"es the bullets from the list items. , then absolutely position each list item bo( as , see fit, resulting in a bo( in the normal flo ith three lin!s 4/igure <>5.

$igure )*#.elati"ely absolute- 3sing a combination of positioning to !eep li!e items together ithin normal flo .

,f the bro ser is resized, e"erything ill flo normally, but the absolutely positioned elements ill retain their position ithin the relati"e bo(.

Stac0ing 4rder: C9index


An important property in CSS is z7inde(. $his property pro"ides us a third "isual dimension of depth ith any positioned element 4note that the element must be positioned to accept a z7inde(5. $his ay, e can stac! bo(es and ha"e them o"erlap as eYd li!e. ,n /igure <?, , created > bo(es and used the follo ing CSS to cause them to o"erlap naturally, ithout using a z7inde(. $his is the default stac!ing order beha"ior hen no z7inde( is in"ol"ed.
div(sam+le1 {+osition a-sol*te$ left 5"+D$ -ac.,ro*nd-color -l*e$& div(sam+leH {+osition a-sol*te$ left 5"+D$ -ac.,ro*nd-color red$& 1"+D$ +addin, R5+D$ +addin,

div(sam+le> {+osition a-sol*te$ left 5"+D$ -ac.,ro*nd-color %ello3$&

11"+D$ +addin,

$igure )+#2efault stac!ing order. $igure )+# 2efault stac!ing order.

, can re"erse the stac! order using the z7inde(div(sam+le1 {+osition a-sol*te$ left 5"+D$ -ac.,ro*nd-color -l*e$ z-indeD 1"+D$ +addin, >$&

div(sam+leH {+osition a-sol*te$ left R5+D$ +addin, 5"+D$ -ac.,ro*nd-color red$ z-indeD H$& div(sam+le> {+osition a-sol*te$ left 11"+D$ +addin, 5"+D$ -ac.,ro*nd-color %ello3$ z-indeD 1$&

Stac0ing 4rder: C9index@ continued


/igure <K sho s the results.

$igure ),#.e"ersing the stac! using z7inde(.

,t is important to understand that the higher the number, the Zcloser[ to the screen the item appears. Also, you do not ha"e to use se'uential numbers. ,n fact, designers ho ant to be "ery certain that a gi"en element is al ays on top of a stac! might use numbers significantly higher than those lo er in the stac!div(sam+le1 {+osition a-sol*te$ left 5"+D$ -ac.,ro*nd-color -l*e$ z-indeD 1"+D$ +addin, H$&

div(sam+leH {+osition a-sol*te$ left R5+D$ +addin, 5"+D$ -ac.,ro*nd-color red$ z-indeD 1"$& div(sam+le> {+osition a-sol*te$ left 11"+D$ +addin, 5"+D$ -ac.,ro*nd-color %ello3$ z-indeD >$&

/igure <: sho s the results, ith the red bo( coming to the foreground.

$igure )/#Bringing a bo( to the foreground ith z7inde(.

Another point to ma!e regarding z7inde( is that each positioning conte(t allo s for a ne instance of z7inde(. $his is hy you might see se"eral instances of the same numbers that result in different stac!ing orders\it *ust depends on hat the designer or de"eloper is attempting to achie"e.

C4RE CSS :RAP9UP


$he goal of the Core CSS series is to ensure that readers are empo ered to understand the areas of CSS that are unclear and confusing, as ell as gi"e insight into the ay bro sers beha"e. 3nderstanding CSS and ho bro ser beha"iors influence the or! you do empo ers you to en"ision, create and code to a high 'uality that ill allo the sites and applications you design to be manageable, scalable and attracti"e, too.

Вам также может понравиться