英文教程:五种CSS选择器类型



英文教程:五种CSS选择器类型. CSScommandsareusuallygroupedinthecurlybracestomakeasetofrules.FollowingarethevariouswaysavailabletoattachthesesetofruleswithHTMLcode.
Selector(insimplewords)meanshowyounamethesesetofrules.
1CLASSSelectORS
ClassselectorsisthesimplestformofselectorswhereyouassignyourownmeaningfulnametothesetofCSSrules.Tocreateaclassselectoryousimplyneedtowritenameoftheclassfollowedbyaperiod.
(Aclassnamecannotstartwithanumberorasymbolasitisnotsupportedbyvariousbrowsers.)
Forexample,
p.big{font-weight:bold;font-size:12px;}
.center{text-align:center;}
AndthisHTML:
<pclass="big">Thisparagraphwillberenderedbold.www.phpstudy.net</p>
Youcanapplymorethanoneclasstoagivenelement.
AndthisHTML:
<pclass="centerbig">Thisparagraphwillberenderedbold.</p>
Intheaboveexample.bigand.centerarenameofCSSclassesandtheseclassesareappliedtoPtaginHTML.
IfclassnameisfollowedbyHTMLelementinyourCSScodelikep.biginaboveexampleitmeansthatthisclasswillworkonPtagonly.
OtherwiseyoucanapplytheCSSclassonanyelement.
It’sagoodpracticetoaddHTMLelementbeforeclassnameinCSSifyouarewritingCSSrulesforaparticularelement(ItaddsmoreclaritytoCSScode.
2IDSelectORS
IDselectorsworklikeclassselectors,exceptthattheycanonlybeusedononeelementperpagebecausetheyworkwithIDofthehtmlelement.TheidselectorisdefinedasidoftheHTMLelementfollowedbya#symbol.
Forexample,
p#navigation{width:12em;color:#666;font-weight:bold;}
AndthisHTML:
<pid="navigation">Thisparagraphwillberenderedbold.www.phpstudy.net</p>
AsagoodpracticeIDselectorsmustbeusedifyouarewritingtheCSScodeforasingleHTMLelementonly.IDselectorsarewellsupportedacrossstandards-compliantbrowsers.
3TAGSelectOR
TagselectorisanothersimplemethodofCSSrulesimplementation.YoucanusethisselectortoredefinetherulesforaparticularHTMLelement.
Forexample:
p{color:#999;font-weight:bold;}
IntheaboveexampleCSScodewillbeautomaticallyappliedoneveryptag.
4DESCENDENTSelectORS
Descendentselectorsspecifythatstylesshouldonlybeappliedwhentheelementinquestionisadescendent(forexample,achild,oragrandchild)ofanotherelement.
Forexample,
h3em{color:white;background-color:black;}
AndthisHTML:
<h3>Thisis<em>emphasized</em>www.phpstudy.net</h3>
Intheaboveexampleemisdescendentofh3element.Abovecssrulewillautomaticallybeappliedonallemelementsinsideh3elementintheHTMLcode.Descendentselectorsarewellsupportedacrossstandards-compliantbrowsers.
5GROUPINGSelectORS
Youcanalsospecifythesamesetofrulesformorethanoneselctor,likethis:
p,h1,h2{text-align:left;}
Justplaceacommabetweeneachone.
Youcanevengetmorecomplex,andgroupmultipleclassandidselectors:
p.navigation,h1#title{font-weight:bold;}

« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3