Você está na página 1de 10

CREATE A STUNNING

MENU IN CSS3
BY ALEX BALL

CSS, WEB DESIGN AUG 3, 2012

TheadventofCSS3hasintroducedaworldof
possibilitiesforwebdesignersanddevelopers.Withanimations,shadows,rounded
cornersandmore,elementscanbeeasilystyled,andstillweighlessthanever
before.
Thenavigationofawebsiteisoneofthemostfundamentalaspectstomakeorbreak
ausersexperience.Insteadofloadingyourmenudownwithindividualimagesor
sprites,whynotdotheentirethinginCSS3?
NoneedforjQueryorJavaScript;noneedtolaunchPhotoshop.Andletstakeitup
anotchbyincludingagreaticonfonttoaddsomecharactertoourmenu.
Sograbyourfavoritecupofcoffee(orifyourelikeme,anicecoldDietCoke),
openupyourfavoritecodeeditor,andletsmakeaslicknavigationmenuusingonly
CSS3.

BEFORE WE GET STARTED

Beforewediveintothecodeforourmenu,Idliketogooversomeoftheassetsand
toolswelluseinthistutorial,whichyoucandownloadandusewhileyoufollow
along.Theseareallincludedinthe.zipfileattheend,whichalsoincludesthefinal
code.
Backgroundimage:Dark

DenimfromSubtlePatterns.
TextFont:Droid

SansfromGoogleWebFonts.

IconFont:Iconic

IconSetfromSomeRandomDude.
CSS3JavaScript:prefixfreefromLeaVerou.
Alright,gotallthose?Oratleastdownloadedthemwiththefull.zipfile?Great,
nowletsgetstarted.Wellwalkthroughthesetupinpieces,startingwiththe
HTML,thenthebasicCSS,andfinallyspicingitupwithCSS3.

THE HTML

o
o

o
o
o
o

o
o
o
o
o
o

o
o

SincewerebeingprogressivewithCSS3inourmenusystem,Iwentaheadandset
usupwithaverybasicHTML5setup.Noneedtogocrazyherewerenot
buildingoutanentiresiteinthistutorial,justthemenu.
Letsjumpintothecodeforthemenu.Themenuisjustasimpleunorderedlist,
withnestedlistsfordropdowns.TheunorderedlistiswrappedinanHTML5tag.
Home
About
CompanyHistory
Meettheteam
Services
WebDesign
AppDevelopment
EmailCampaigns
Copyrighting
Products
WidgetOne
WidgetTwo
WebAppThree
WebAppFour
CrazyProducts
iPhoneApps
Contact
ContactUs
Directions

Asyoucansee,wevegotfivemenuitems,fourofwhichhavesubitems.Thenext
stepistogetthebasicCSSstylingdone,thenwellapplytheCSS3tothemenu,and
thespanstoachievetheicons.

THE CSS
Togetagoodbaselinetoworkwith,welladdthedenimpatternfromSubtle
Patternsandcenterthemenu,basedona960.gsgrid.Wellalsocreateaclearfix
class,whichisusedinourmenusystems.
/* http://meyerweb.com/eric/tools/css/reset/ v2.0 | 20110126
License: none (public domain) */ html, body, div, span, applet,
object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr,
acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s,
samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt,
dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody,
tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure,
figcaption, footer, header, hgroup, menu, nav, output, ruby,
section, summary, time, mark, audio, video {
margin: 0;

padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline; } /* HTML5 display-role reset for older
browsers */ article, aside, details, figcaption, figure, footer, header,
hgroup, menu, nav, section {
display: block; } body {
lineheight: 1; } ol, ul {
list-style: none; } blockquote, q {
quotes:
none; } blockquote:before, blockquote:after, q:before, q:after {
content: '';
content: none; } table {
border-collapse: collapse;
border-spacing: 0; } body {
background: url('img/denim.png');
font-family: 'Droid Sans', sans-serif;; } .clearfix {
clear: both; }
.wrap {
width: 940px;
margin: 4em auto; }
Now,wellgettoworkonstylingthemenu.First,westylethetoplevelnavigation
tocreateaverybasicframework.
nav {
padding: 0 10px;
position: relative; } .menu li {
float:
left;
position: relative; } .menu li a {
color: #444;
display:
block;
font-size: 14px;
line-height: 20px;
padding: 6px
12px;
margin: 8px 8px;
vertical-align: middle;
textdecoration: none; } .menu li a:hover {
color: #222; }

Letswalkthroughthatcode.Themenubarisgoingtospanthefullwidthofthe
.wrapclass,whichis940pixels.Toaddabitofwhitespaceforthefirstmenuitem,
weadd10pixelsofpaddingontheleftandrightside,andsetthepositionofthenav
bartorelative.Thisbecomesaveryimportantdeclarationlater.Thetoplevelmenu
itemsarefloatedleft,andalsohavearelativepositioning.Thenwetakeastep

furtherandstylethelinks,whicharesettodisplay:block;.Thisisdifferentfrom
severalCSSmenusystemsouttherewhichhavedisplay:inline;declared.

THE DROPDOWN
Thedropdownmenusarenestedunorderedlists,soletsstylethemnext.Again,
weregoingwiththebasicCSShere.
/* Dropdown styles */ .menu ul {
position: absolute;
left:
-9999px;
list-style: none; } .menu ul li {
float: none; } .menu
ul a {
white-space: nowrap; } /* Displays the dropdown on hover
and moves back into position */ .menu li:hover ul {
left: 5px; } /*
Persistent Hover State */ .menu li:hover a {
color: #222; }
.menu li:hover ul a {
background: none; } .menu li:hover ul li
a:hover { }

What?Wheredourmenugo?Remember,thisisaworkinprogress.Itwillstartto
cometogether,Ipromise.The.menuulsetsthepositiontoabsolute(remember,this
unorderedlistisinsidethetoplevellistitem,whichispositionedrelativelythus,
the.menuulispositionedrelativelytothetoplevellistitem).Then,wepositionit
wayoffscreen.ThisisatechniqueIpickedupfromCSSWizardy,asthismethod
providesbetteraccessibilityforscreenreaders,etc.Later,wellcallitbackonour
hoverstates.

Next,wesetthedropdownlistitemstofloatleft,creatingauniformlookforthe
dropdownitem.Ontheanchortag,wethrowinawhitespace:nowrap;which
preventslonglinksfromwrappingontotwolines.Thishelpsmaintainauniform
lookandkeepstheuserinterfaceeasytouse.
Movingontothehoverstates,whenhoveringonthetoplevellistitem(.menuli)we
throwonahoverandtargetoursubunorderedlists,andmovethelistfromwayoff
screento5pixelstotheleftofthelistitem.Again,thepositioningisrelativetothe
toplevellistitem,soitisoffsetby5pixelsfromthelistitem.Ifyouweretoremove
therelativepositionofthetoplevelli,allofyourhoverswouldflyoutunderthe
Homelink.
Now,wellmakesurethatwhenwerehoveringonourdropdowns,thetoplevelli
maintainsthestyling,but,thedropdownmenuitemsdonthavethatstyle.Thatis
whereyour.menuli:hoveraand.menuli:hoverulacomeintoplay.Theformersets
thepersistenthoverstate(somakethisthesameasyourtoplevelstyle),andthe
latterremovesthatstylingfromthesubnavigationlists.
Finally,westylethedropdownmenuitems.Oh,itsblank?Yeah,itsallCSS3.
Wellgettothatinaminute.

THE CSS3
Nowwegettothefunpart.TheCSS3specificationhasintroducedalotoffunand
excitingtoolstowebdesignersanddevelopersutilizingmodernwebbrowsers.Sure,
notallbrowserssupportalloftheCSS3specs(checkoutcss3files.comforagreat
primeronwhatworksandwhatdoesnt),butmanyofthespecificationsdegrade
gracefullyanddonotbreakthedesign.
Note:forthistutorial,ImusingLeaVerouspowerfulandepicallytiny(2kb)
prefixfree.jsscript.IfyouhaventuseditbeforeandyouworkwithCSS3,do
yourselfafavorandcheckitout.Itusessomecrazyadvanceddetectiontotake
CSS3declarationsandaddtheappropriatevendorprefixestoensurebrowser
compatibilitywhenneeded.Itkeepsthecodealotcleanerandmakesthetutorial
easiertounderstand.
LetsaddsomeCSS3tothenavigationbar,thetoplevelunorderedlistandlist
items.
nav {
background: -webkit-gradient(linear, center top, center
bottom, from(#fff), to(#ccc));
background-image: lineargradient(#fff, #ccc);
border-radius: 6px;
box-shadow: 0px 0px
4px 2px rgba(0,0,0,0.4);
padding: 0 10px;
position: relative; }
.menu li a:hover {
background: -webkit-gradient(linear, center
top, center bottom, from(#ededed), to(#fff));
backgroundimage: linear-gradient(#ededed, #fff);
border-radius: 12px;

box-shadow: inset 0px 0px 1px 1px rgba(0,0,0,0.1);


}

color: #222;

Firstupintheabovecodeisthenavigationbar.Weaddalineargradientfromwhite
toalightgray(usingboththestandardgradientdeclaration,andtheoldwebkit
styletomaintaincompatibilitywitholderbrowsers.Weroundout(nopunintended)
thenavbarwitha6pixelborderradius.
Ontothehoverstates:weaddanoppositelineargradient,aswellassomerounded
corners,andaninsetboxshadow,givingourlinkstheappearancethatthemenu
itemdropsintothenavbar.Overall,averycleanlook.Beforewegettothehover
states,IwanttorevisitsomeoftheHTMLinconnectionwithsomeCSS3.Iuseda
greaticonfontcalledIconicbySomeRandomDude,whichisembeddedwiththe
CSS3@fontfaceproperty,andthencalledwithspantagsonthemenuitems.Once
youdownloadtheset,youcansnagthecodefromtheCSSinthezipfile,aswellas
copyoverthefontfiles.Ifyouchangetherelativepath,remembertochangethesrc
inthe@fontface.
@font-face {
font-family: 'IconicStroke';
src:
url("fonts/iconic/iconic_stroke.eot");
src: local('IconicStroke'),
url("fonts/iconic/iconic_stroke.svg#iconic") format('svg'),
url("fonts/iconic/iconic_stroke.otf") format('opentype'); } .iconic {
color:inherit;
font-family: "IconicStroke";
font-size: 38px;
line-height: 20px;
vertical-align: middle; }

Withthatfontdeclaration,youcannowstylespantagswithspecificclassesto
createtheicons.Formyproject,Ikeepiconic.cssasafullyintactstylesheetnamed
aftermystyle.css.Toincorporatetheiconsinmymenus,wellaltertheHTML
slightly:
Home
About
Services
Products
Contact
Obviously,thecodeaboveonlyupdatesthetoplevelnavigation,byaddingaspan
tagwiththeclassiconicandtheappropriateiconclass.Sonowthatthatisdone,
welldothefinalstylingofthedropdownmenuitems,whichthrowinsomenew
CSS3propertieslikeopacityandatransition.Sofirst,the.menuul:
.menu ul {
position: absolute;
left: -9999px;
list-style: none;
opacity: 0;
transition: opacity 1s ease; }
Thetwobigpropertiestoreviewherearetheopacityandtransitiondeclarations.
Opacityissetto0,andthetransitionwillmakethedropdownmenugofroman
opacityof0toanopacityof1overthecourseof1second.Nowletsdothehover
state.
.menu li:hover ul {
background: rgba(255,255,255,0.7);
border-radius: 0 0 6px 6px;
box-shadow: inset 0px 2px 4px
rgba(0,0,0,0.4);
left: 5px;
opacity: 1; }

Thehoverstateisafairlycomplexonetothinkabout.Letsgolinebyline.
Thetoplinemakesthebackgroundapurewhitebackground,thensetstheopacityto
70%toletsomeofthebackgroundpatternpeekthrough.
Secondly,Iveroundedthebottomtwocorners,leavingthetopcornerssquaredoff
togivetheallusionthatthedropdowniscomingoutfromthenavbar.
Butthethirdlineiswherethemagiccomesin.Duetothepositioningofthe
navigationbarandlistitems,theuseofzindexisvirtuallyimpossibleforlayering
togetanappropriateaffect.Toachievetheappearancethatthedropdownisbeneath
thenavbar,wesetalight,similarinsetboxshadowthatcomesdownintothedrop
down.Finally,settheopacityto1,whichcoordinatestothetransitionwesetearlier.
TherestoftheCSS3isprettystraightforward,andlargelyrepetitiveofwhatweve
goneoveralready:
.menu li:hover a {
background: -webkit-gradient(linear, center
top, center bottom, from(#ccc), to(#ededed));
backgroundimage: linear-gradient(#ccc, #ededed);
border-radius: 12px;
box-shadow: inset 0px 0px 1px 1px rgba(0,0,0,0.1);
color: #222;
} .menu li:hover ul a {
background: none;
border-radius: 0;
box-shadow: none; } .menu li:hover ul li a:hover {
background:
-webkit-gradient(linear, center top, center bottom, from(#eee),
to(#fff));
background-image: linear-gradient(#ededed, #fff);
border-radius: 12px;
box-shadow: inset 0px 0px 4px 2px
rgba(0,0,0,0.3); }
Shouldntbetoomuchoutoftheordinaryinthatlastsetofcode.Andtakealookat
ourfinalresult.

CONCLUSION
Wellthereyouhaveit;aslickandsmoothCSS3menu.Iveincludedallofthe
assetsinazipfile,whichyoucandownload

here,oryoucanview
thedemohere.

Você também pode gostar