8/12/2019 core CSS
1/41
Core CSS: Part IBy Molly E. Holzschlag
About CSSAs 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. Hoe"er, most
people ha"e learned CSS the same ay they#"e learned H$M%,by "ieing source, copying template
codes, reading boo!s and articles. While this &bootstrap& method of learning is often the best ay tofind great techni'ues, it may not be the best for !noing 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 thembetter 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"esSE1 4search engine optimization5 impro"es
$he first proposal for CSS as made by H6!on Wium %ie, no C$1 of 1pera Softare. He or!ed
ith Bert Bos to co7author the first CSS specification, hich belie"e it or not, became a
8/12/2019 core CSS
2/41
recommendation in 899:+ By 899; CSS
8/12/2019 core CSS
3/41
$igure "#2ocument 4mar!upcontent5D 0resentation 4CSS5D Beha"ior 4a"aScript5
1f course, *ust because e &ba!e& our three7layered ca!e separately, it all has to come together and *ustbe &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 brosers e use.
%earning and Imlementation Cur&es
Hoe"er, there#s been difficulty along the road to adopting, learning and managing CSS. $his difficulty
is due to a number of influences, but to of the ma*or concerns are a steep learning cur"e and lac! ofconsistent broser implementation of specifications.
Especially of challenge for "isual designers is that CSS nomenclature and concepts are programmatic
rather than graphic7design oriented 4$able
8/12/2019 core CSS
4/41
or!arounds, hac!s, filters and a"aScript patchor! to repair problems across broser and broser
"ersions. Error handling is a particularly frustrating part of this, particularly as Web brosers
implement different "ersions of different specifications at different times 4/igure 5.
8/12/2019 core CSS
5/41
$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 broser to match any h8, color it red, size it relati"ely to ;=J and apply the erdana
typeface 4/igure ?5-
$igure +#Adding additional declarations to the rule.
'rammar Purose Examles
Selector
A selector chooses 4&selects&5 an element ithin
mar!up documents to be styled. $here are many
selector types in CSS
8/12/2019 core CSS
6/41
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 curlyhair, 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 isan 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, hoe"er most are. Authors can tap into the poer of inheritance by alloinginheritable properties to be inherited by their children or descendents, or prohibit inheritance if so
desired.
Style S(eet !yes
$here are three primary types of style sheets as follos- -ro.ser#$he broser style sheet is the default style of a gi"en broser. t is either an actual
.css file such as e find in Mozilla brosers, or hard coded into the softare. Broser styles aredifferent beteen brosers and "ersions, so being aare of them is e(tremely important.
Where"er you do not supply a style, the broser style ill be used instead.
User#3ser style sheets are a great concept that has unfortunately not been brought to bear on alarge 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
broser.
Aut(or#$he author is you+ $hat is, author styles are those styles that the de"eloper or designeris 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 !eyords.
$he proper use for +important is to create a balance beteen author and user style sheets, a necessityfor 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
to places- As a diagnostic tool hich you remo"e from the declaration after debugging a problemD andin a user style sheet. 1therise, please a"oid usage at all costs.
8/12/2019 core CSS
7/41
Aut(or Style S(eets by !ye
$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. @omatter 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 folloing paragraph element-
2his +arara+h is st%led onl% % defa*ltro3ser st%les
$he style is placed ithin the style attribute as a "alue-
2his +arara+h 3ill no3have a l*e color)
/igure : shos 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!upand CSS, ha"e ad"ised that using this techni'ue isn#t really separating presentation from the documentat 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.
Scenario Issues -est Practice
nline style in
small "ersus
large Websites
f you ha"e a "ery small site 48= documents orless5 the ris! of losing trac! of inline styles is
less than if you are or!ing on "ery large
sites, here it#s easy to lose trac! of inlinestyles unless they are meticulously
documented. And ho does thatL
A"oid use of inline style in almost all
professional eb sites, and in particular
those sites hich are large or e(pected togro significantly.
nline style
for debuggingpurposes
As the section on &specificity& illdemonstrate, an inline style has the highest
specificity of any other rule that might be
trying to style the element in 'uestion. f youare ha"ing trouble getting to the heart of the
matter, dropping an inline style into the
element you are ha"ing trouble ith can help
determine that in fact, there#s a conflict.
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 conflictingsomehere that need to be found. /ind
the conflicts, repair the rules, and remo"e
the diagnostic inline style prior to
publishing+
8/12/2019 core CSS
8/41
Scenario Issues -est Practice
nline style as
&'uic!& fi(es4a!a laziness5
$here are "ery fe benefits from using inline
style, but one find that#s great is for 'uic!fi(es and blog posts, hich you can do on the
fly.
2espite the fact that do this myself, it#s
not something #d recommend,particularly for professional sites.
!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 follos-
6ore 6 9Dam+les+ {color l*e$&n this case, all +arara+hs on the +ae 3illt*rn l*e)
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 andstructure, but only in that same document. $able K pro"ides some insights into the best ays to use
embedded style.
Scenario Issues -est Practice
Embedded
style in small
"ersus largeWeb sites
f you ha"e a eblog ith one templatedocument that controls your entire site, it is
feasible to use embedded style in this
instance. Hoe"er, in any professional siteor app de"elopment, a"oid using embedded
style, for it, li!e inline style, can contribute
to confusion hen debugging.
A"oid in professional practice.
Embedded
style fordebugging and
or!flo
purposes
As ith inline styles, if you#re trying to
isolate hy a gi"en style isn#t applying, you
can use embedded style to or! throughsome conflicts. Another use that findhelpful is that during de"elopment, li!e to
or! in one document, embedding my
styles and building out the content andmar!up all in the same place.
$hough not ideal, embedded style can be
used to debug and find conflicts in the case
of multiple style sheets. Wor!fload"antages as described can be useful, theone ca"eat in all instances of professional
sites- emo"e your embedded styles out to
appropriate e(ternal styles after you#re doneor!ing, test, and you#re good to go.
Embedded
style as&'uic!& fi(es
Where is that styleL What if you ant to
use it again more efficientlyL
A"oid publishing embedded style sheets.
8/12/2019 core CSS
9/41
Scenario Issues -est Practice
4a!a laziness5
!able ,#Best 0ractices- Embedded Style
%in0ed 1External Style2
%in!ed style is the true &holy grail& of style sheet types. t pro"ides us ith the broadest application of
styleD allos us to manage the presentational aspects of a site from a handful of style sheetsDperformance is faster due to the broser 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-
n almost all cases, the lin!ed style sheet is the one you ill be or!ing ith most.
Be careful ith case matching beteen your CSS and H$M% documents. f you create a selector H8 inupper 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 loer case 4this is re'uired in H$M%5 and
!eeping CSS loer case as ell, helping to a"oid potential case7related conflicts. Also, hile manyprogrammers 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.
Alication 3ierarc(y and Sort 4rder
1f course, most or!ing Web de"elopers and designers are ell aare that or!ing ith CSS *ust can#t
be that straight forard+ $here are many reasons hy CSS is as broad in scope as it is, but fle(ibility
and poer are to of the most credible reasons for hy you can approach a gi"en problem ithnumerous 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 poerful 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
on identity. $his is a "ery common large7organization issue, and one hich ine"itably leads to
8/12/2019 core CSS
10/41
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 broser, 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 broser 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 somehat accurate but also a bitmisleading.
Sort order, the term that is used to describe the sorting of multiple CSS rules, is the process by hich a
Web broser sorts the rules it is gi"en. f e ha"e a scenario here there are to lin!ed style sheets, an
embedded sheet in the document in 'uestion, and an inline style, the broser has to sort through thoseand resol"e sort conflicts. Consider this H$M% -
+ {font-famil% 2imes$&Which font 3ill this eFWhat ao*t this +arara+hF
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 somehere in the first to had
conflicting rules that styled paragraphs using the Pene"a font, the sort order process ill see the laststyle 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 alays &trump& another style in a scenario li!e this.
Secificity
$here is one final deal7brea!er for the rules of Cascade and sort, and that is the specificity of a gi"enselector. #"e !ept the e(amples here simple for a reason as selectors are complicated and actually ta!e
8/12/2019 core CSS
11/41
up about a third of the Core CSS series.
Specificity is an algorithm ith a broad base that allos 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 specificrule is applied no matter here the rule resides in the sort.
Consider the folloing rule-
(content + {font-famil% Garamond$&
$his is a combination of an 2 selector 4Fcontent5 and an element selector 4p5. $he space beteen the
to 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 inParamond, 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 rulesin the e(act order shon in $able :.
Examle Count 6 of ID SelectorsCount 6 of Class SelectorsCount 6 of Element Selectors
ul =, =, 8
Fcontent ul li 8, =, shos 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 folloing H$M%-
@ar%, @ar%, P*ite contrar%,ho3 does %o*r arden ro3FAnd sheIs *%in a tair3a% toHeavenCoses are red, violetsare 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 hoe"er that in the case of hyphen matching,
order matters. $he hyphenated ord must be first in the string. Had e sitched the third paragraph#sattribute 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 aare, as described in $able ?.
Pseudo
ElementPurose Examle
-first7lineSelects only the first line of te(t in a gi"en
element.
bloc!'uote-first7line font7eight-
boldDI
8/12/2019 core CSS
22/41
Pseudo
ElementPurose Examle
-first7letterSelects only the first letter of te(t in a gi"enelement
p-first7letter font7size-
8/12/2019 core CSS
23/41
8/12/2019 core CSS
24/41
$igure "7#While e can "isually see the generated content on the screen, it does not appear ithin theactual 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! ofimplementation for the eforeand afterpseudo elements.
Combining Selectors
Selectors can be combined, gi"ing authors highly specific ays of or!ing to style and manage
documents.
'rouingSelector grouping is simply placing a number of selectors that all share common properties separated
by commas-
h1, h, h, hN, h5, hR, +, P, loc.P*ote, td,(content, )standard {color ($ marin 5+D$&
@o all these selectors ill share the declaration properties.
Prouping is useful hen you ha"e a lot of shared features beteen elements. )ou can group thoseelements as shon, 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 !yes
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 shos some e(amples
as ell as the selectors definition,and to help you practice,the selector#s specificity. ead selectors from
8/12/2019 core CSS
25/41
the right of the selector,it helps+
Combined Selector MeaningSecificity
1CSS )2
Fcontent di".module T p
Selects child paragraphs descending from aelement that has a class of &module& and is ithin the
uni'uely identified portion of the document that is
identified as &content&
8,8,5.
8/12/2019 core CSS
34/41
$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 allos the subse'uentelements 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 e can create a footer beneath the
floated columns.
$here are numerous ays to clear floats. A "ery popular one is the creation of a clear class and the useof 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-
or
My preference of the to 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 and8:5.
$igure ",#$he float is properly cleared. @otice ho the column to the left doesnYt fill the entire a"ailable space\this isnormal beha"ior. $he important issue is that the bottom7most element is cleared and does not try to Zcreep up[ into the
a"ailable space.
8/12/2019 core CSS
35/41
$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 poerful piece of CSS that allos 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 reallyas, 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 4seeelati"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-
8/12/2019 core CSS
36/41
8/12/2019 core CSS
37/41
$igure ">#@ormal flo, again.
$igure ">#@ormal flo, again.
$igure )
8/12/2019 core CSS
38/41
8/12/2019 core CSS
39/41
*l(s*-nav {+osition relative$ 3idth 5+D$ +addinN+D$ order 1+D solid lac.$& then st%led the list items and lin.sli {list-st%le-t%+e none$&a {teDt-decoration none$&li(home {+osition asol*te$ 3idth 1+D$ left 1+D$order 1+D solid reen$&li(+rod*cts {+ositionasol*te$ 3idth 1+D$
asol*te$ left 1+D$ order 1+D solid red$&li(contact {+osition asol*te$ 3idth 1+D$ leftN+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 broser is resized, e"erything ill flo normally, but the absolutely positioned elements ill
retain their position ithin the relati"e bo(.
Stac0ing 4rder: 9index
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
8/12/2019 core CSS
40/41
8/12/2019 core CSS
41/41
/igure