CascadedStyleSheet
INTRODUCTIONTOCSS
WhatisCSS?
CSSstandsforCascadingStyleSheets StylesdefinehowtodisplayHTMLelements StylesarenormallystoredinStyleSheets StyleswereaddedtoHTML4.0tosolveaproblem ExternalStyleSheetscansaveyoualotofwork ExternalStyleSheetsarestoredinCSSfiles Multiplestyledefinitionswillcascadeintoone
StyleSheetsCanSaveaLotofWork Styles sheets define HOW HTML elements are to be displayed, just like the font tag and the color attributeinHTML3.2.Stylesarenormallysavedinexternal.cssfiles.Externalstylesheetsenableyou to change the appearance and layout of all the pages in your Web, just by editing one single CSS document! CSSisabreakthroughinWebdesignbecauseitallowsdeveloperstocontrolthestyleandlayoutof multipleWebpagesallatonce.AsaWebdeveloperyoucandefineastyleforeachHTMLelement andapplyittoasmanyWebpagesasyouwant.Tomakeaglobalchange,simplychangethestyle, andallelementsintheWebareupdatedautomatically. MultipleStylesWillCascadeintoOne Style sheets allow style information to be specified in many ways. Styles can be specified inside a singleHTMLelement,insidethe<head>elementofanHTMLpage,orinanexternalCSSfile.Even multipleexternalstylesheetscanbereferencedinsideasingleHTMLdocument. CascadingOrder WhatstylewillbeusedwhenthereismorethanonestylespecifiedforanHTMLelement? Generallyspeakingwecansaythatallthestyleswillcascadeintoanewvirtualstylesheetbythe followingrules,wherenumberfourhasthehighestpriority: 1. 2. 3. 4. Browserdefault Externalstylesheet Internalstylesheet(insidethe<head>tag) Inlinestyle(insideanHTMLelement)
So,aninlinestyle(insideanHTMLelement)hasthehighestpriority,whichmeansthatitwill overrideastyledeclaredinsidethe<head>tag,inanexternalstylesheet,orinabrowser(adefault value).
CSSSyntax
TheCSSsyntaxismadeupofthreeparts:aselector,apropertyandavalue: Ex: Selector Property Value
selector{property:value}
The selector is normally the HTML element/tag you wish to define, the property is the attributeyouwishtochange,andeachpropertycantakeavalue.Thepropertyandvalueare separatedbyacolon,andsurroundedbycurlybraces:
body { color: black }
Ifthevalueismultiplewords,putquotesaroundthevalue:
p { font-family: "sans serif " }
If you wish to specify more than one property, you must separate each property with a semicolon.Theexamplebelowshowshowtodefineacenteralignedparagraph,withared textcolor: p {text-align:center;color:red} Tomakethestyledefinitionsmorereadable,youcandescribeonepropertyoneachline,like this:
p { text-align: center; color: black; font-family: arial
Grouping
You can group selectors. Separate each selector with a comma. In the example below we have grouped all the header elements. All header elements will be displayed in green text color:
h1,h2,h3,h4,h5,h6 { color: green }
TheclassSelector
WiththeclassselectoryoucandefinedifferentstylesforthesametypeofHTMLelement. Say that you would like to have two types of paragraphs in your document: one right alignedparagraph,andonecenteralignedparagraph.Hereishowyoucandoitwithstyles:
p.right {text-align: right} p.center {text-align: center}
YouhavetousetheclassattributeinyourHTMLdocument:
<p class="right"> This paragraph will be right-aligned. </p> <p class="center"> This paragraph will be center-aligned. </p>
Toapplymorethanoneclasspergivenelement,thesyntaxis:
<p class="center bold"> This is a paragraph. </p>
TheparagraphabovewillbestyledbytheclasscenterANDtheclassbold.
AddStylestoElementswithParticularAttributes
YoucanalsoapplystylestoHTMLelementswithparticularattributes. Thestylerulebelowwillmatchallinputelementsthathaveatypeattributewithavalueof text:
input[type="text"] {background-color: blue}
TheidSelector
YoucanalsodefinestylesforHTMLelementswiththeidselector.Theidselectorisdefined asa#. Thestylerulebelowwillmatchtheelementthathasanidattributewithavalueofgreen:
#green {color: green}
CSSComments
Commentsareusedtoexplainyourcode,andmayhelpyouwhenyoueditthesourcecode atalaterdate.Acommentwillbeignoredbybrowsers.ACSScommentbeginswith/*, andendswith*/,likethis:
/* This is a comment */
HowtoInsertaStyleSheet
Whenabrowserreadsastylesheet,itwillformatthedocumentaccordingtoit.Thereare threewaysofinsertingastylesheet: 1. ExternalStyleSheet 2. InternalStyleSheet 3. InlineStyles
ExternalStyleSheet
Anexternalstylesheetisidealwhenthestyleisappliedtomanypages.Withanexternal stylesheet,youcanchangethelookofanentireWebsitebychangingonefile.Eachpage mustlinktothestylesheetusingthe<link>tag.The<link>taggoesinsidetheheadsection:
<head> <link rel="stylesheet" type="text/css" href="mystyle.css" /> </head>
Thebrowserwillreadthestyledefinitionsfromthefilemystyle.css,andformatthe documentaccordingtoit. Anexternalstylesheetcanbewritteninanytexteditor.Thefileshouldnotcontainanyhtml tags.Yourstylesheetshouldbesavedwitha.cssextension.Anexampleofastylesheetfile isshownbelow:
hr {color: sienna} p {margin-left: 20px} body {background-image: url("images/back40.gif")}
InternalStyleSheet
Aninternalstylesheetshouldbeusedwhenasingledocumenthasauniquestyle.You defineinternalstylesintheheadsectionbyusingthe<style>tag,likethis:
<head> <style type="text/css"> hr {color: sienna} p {margin-left: 20px} body {background-image: url("images/back40.gif")} </style> </head>
Thebrowserwillnowreadthestyledefinitions,andformatthedocumentaccordingtoit.
InlineStyles
Aninlinestylelosesmanyoftheadvantagesofstylesheetsbymixingcontentwith presentation.Usethismethodsparingly,suchaswhenastyleistobeappliedtoasingle occurrenceofanelement. Touseinlinestylesyouusethestyleattributeintherelevanttag.Thestyleattributecan containanyCSSproperty.Theexampleshowshowtochangethecolorandtheleftmarginof aparagraph:
<p style="color: sienna; margin-left: 20px"> This is a paragraph </p>
MultipleStyleSheets
Ifsomepropertieshavebeensetforthesameselectorindifferentstylesheets,thevalueswill beinheritedfromthemorespecificstylesheet. Forexample,anexternalstylesheethasthesepropertiesfortheh3selector:
h3 { color: red; text-align: left; font-size: 8pt }
Andaninternalstylesheethasthesepropertiesfortheh3selector:
h3 { text-align: right; font-size: 20pt }
Ifthepagewiththeinternalstylesheetalsolinkstotheexternalstylesheetthepropertiesfor h3willbe:
color: red; text-align: right; font-size: 20pt
Thecolorisinheritedfromtheexternalstylesheetandthetextalignmentandthefontsizeis replacedbytheinternalstylesheet.
CSSBackground
TheCSSbackgroundpropertiesdefinethebackgroundeffectsofanelement. TheCSSbackgroundpropertiesallowyoutocontrolthebackgroundcolorofanelement,set animageasthebackground,repeatabackgroundimageverticallyorhorizontally,and positionanimageonapage.
PossibleValues
1. 2. 3. 4. 5.
backgroundcolor backgroundimage backgroundrepeat backgroundattachment backgroundposition
backgroundcolor
Thebackgroundcolorpropertysetsthebackgroundcolorofanelement. Thecolorvaluecanbeacolorname(red),argbvalue(rgb(255,0,0)),orahexnumber (#FF0000)
p { background-color: #00FF00 }
thetransparentisDefault.Thebackgroundcoloristransparent
p { background-color: transparent }
Example:Thisexampledemonstrateshowtosetthebackgroundcolorforanelement.
<html> <head> <style type="text/css"> body {background-color: yellow} h1 {background-color: #00FF00}
h2 {background-color: transparent} p {background-color: rgb(250,3,255)} </style> </head> <body> <h1>Ganpat University</h1> <h2>U.V.Patel Collge of Engineering</h2> <p>Computer Engineering/Information Technology</p> </body> </html>
Output:
backgroundimage
Thebackgroundimagepropertysetsanimageasthebackground.
PossibleValues
url(URL) : none :
Thepathtoanimage Default.Nobackgroundimage
body { background-image: url(uvpce.gif); }
Example:Setanimageasthebackground <html> <head> <styletype=text/css> body { backgroundimage:url(computer.jpg) } </style> </head> <body> </body> </html> Output:
backgroundrepeat
Thebackgroundrepeatpropertysetsif/howabackgroundimagewillberepeated.
PossibleValues Value Description
repeat repeatx repeaty norepeat
Default.Thebackgroundimagewillberepeatedverticallyand horizontally Thebackgroundimagewillberepeatedhorizontally Thebackgroundimagewillberepeatedvertically Thebackgroundimagewillbedisplayedonlyonce
Example:Howtorepeatabackgroundimage <html> <head> <styletype=text/css> body { backgroundimage:url(gnu.jpg); backgroundrepeat:repeat } </style> </head> <body> </body> </html> backgroundposition
Thebackgroundpositionpropertysetsthestartingpositionofabackgroundimage.
PossibleValues Value Description
Topleft topcenter topright centerleft centercenter centerright bottomleft bottomcenter bottomright X%y%
Ifyouonlyspecifyonekeyword,thesecondvaluewillbe center. Defaultvalue:0%0%
xposypos
Thefirstvalueisthehorizontalpositionandthesecond valueisthevertical.Thetopleftcorneris0%0%.Theright bottomcorneris100%100%.Ifyouonlyspecifyonevalue, theothervaluewillbe50%. Thefirstvalueisthehorizontalpositionandthesecond valueisthevertical.Thetopleftcorneris00.Unitscanbe pixels(0px0px)oranyotherCSSunits.Ifyouonlyspecify onevalue,theothervaluewillbe50%.Youcanmix%and positions.
Example:Howtopositionabackgroundimageusingpixels <html> <head> <styletype=text/css> body { backgroundimage:url(smiley.gif); backgroundrepeat:norepeat; backgroundposition:50px100px; } </style> </head> <body> <p><b>BackGroundImagePosition50px,100px</p> </body> </html> Output:
backgroundattachment
Thebackgroundattachmentpropertysetswhetherabackgroundimageisfixedorscrolls withtherestofthepage.
PossibleValues Value Description
scroll fixed
Default.Thebackgroundimagemoveswhentherestofthe pagescrolls Thebackgroundimagedoesnotmovewhentherestofthepage scrolls
CSSTEXT
TheCSStextpropertiesallowyoutocontroltheappearanceoftext.Itispossibleto changethecolorofatext,increaseordecreasethespacebetweencharactersinatext,aligna text,decorateatext,indentthefirstlineinatext,andmore.
Property Value Description
color direction lineheight
letterspacing textalign
textdecoration
textindent texttransform
wordspacing
color ltr rtl normal number length % normal length left right center justify none underline overline linethrough blink length % none capitalize uppercase lowercase Increaseor decreasethe space between words
Setsthecolorofatext Setsthetextdirection Setsthedistancebetweenlines
Increaseordecreasethespacebetweencharacters Alignsthetextinanelement
Addsdecorationtotext
Indentsthefirstlineoftextinanelement Controlsthelettersinanelement
normal length
Example:Specifythespacebetweencharacters <html> <head> <styletype=text/css> h1{letterspacing:2px} h4{letterspacing:0.1cm} </style> </head> <body> <h1>LetterSpacing</h1> <h4>LetterSpacing</h4> </body> </html> Output:
Example:Decoratethetext <html> <head> <styletype=text/css> h1{textdecoration:overline} h2{textdecoration:linethrough} h3{textdecoration:underline} a{textdecoration:none} </style> </head> <body> <h1>Thisisheader1</h1> <h2>Thisisheader2</h2> <h3>Thisisheader3</h3> <p><ahref=next.htm>RemoveUnderlineinHOTSPOT</a></p> </body> </html>
Output:
Example:Controlthelettersinatext
<html> <head> <styletype=text/css> p.uppercase{texttransform:uppercase} p.lowercase{texttransform:lowercase} p.capitalize{texttransform:capitalize} </style> </head> <body> <pclass=uppercase>Ganpatuniversity</p> <pclass=lowercase>Ganpatuniversity</p> <pclass=capitalize>Ganpatuniversity</p> </body> </html> Output:
CSSFont
TheCSSfontpropertiesallowyoutochangethefontfamily,boldness,size,andthestyleofa text.
PossibleValues
Property
font-style font-variant font-weight font-size/line-height font-family
Value
Description
fontfamily fontsize
fontstyle
fontvariant fontweight
familyname genericfamily xxsmall xsmall small medium large xlarge xxlarge smaller larger length,% normal italic oblique normal smallcaps normal bold bolder lighter 100 200 300 400 500 600 700 800 900
Aprioritizedlistoffontfamilynamesand/orgeneric familynamesforanelement Setsthesizeofafont
Setsthestyleofthefont
Displaystextinasmallcapsfontoranormalfont Setstheweightofafont
Example: Setthefontofatext
<html> <head> <styletype=text/css> h3{fontfamily:times} p{fontfamily:courier} p.sansserif{fontfamily:sansserif} </style> </head> <body> <h3>GanpatUniversity</h3> <p>U.V.PatelCollegeofEngineering</p> <pclass=sansserif>InformationTechnology</p> </body> </html> Output:
Example:Setthestyleofthefont <html> <head> <styletype=text/css> h1{fontstyle:italic} h2{fontstyle:normal} p{fontstyle:oblique} </style> </head> <body> <h1>InformationTechnology</h1> <h2>InformationTechnology</h2> <p>InformationTechnology</p> </body> </html>
Output:
Example:Setthesizeofthefont <html> <head> <styletype=text/css> h1{fontsize:32} h2{fontsize:22} p{fontsize:16} </style> </head> <body> <h1>Thisisheader1</h1> <h2>Thisisheader2</h2> <p>Thisisaparagraph</p> </body> </html> Output:
CSSBorder
The CSS border properties allow you to specify the style and color of an elements border. In HTML we use tables to create borders around a text, but with the CSS border propertieswecancreateborderswithniceeffects,anditcanbeappliedtoanyelement.
Property Value Description
bordercolor border
color borderwidth borderstyle bordercolor borderbottom width borderstyle bordercolor bordercolor borderstyle
Setsthecolorofthefourborders,canhavefromone tofourcolors Ashorthandpropertyforsettingalloftheproperties forthefourbordersinonedeclaration Ashorthandpropertyforsettingalloftheproperties forthebottomborderinonedeclaration
borderbottom
borderbottom color borderbottom style borderbottom width
Setsthecolorofthebottomborder Setsthestyleofthebottomborder Setsthewidthofthebottomborder
thin medium thick length borderleftcolor bordercolor borderleftstyle borderstyle borderleftwidth thin medium thick length borderrightcolor bordercolor borderrightstyle borderstyle borderright thin width medium thick length bordertopcolor bordercolor bordertopstyle borderstyle bordertopwidth thin medium thick length
Setsthecoloroftheleftborder Setsthestyleoftheleftborder Setsthewidthoftheleftborder
SetsthecoloroftheRightborder SetsthestyleoftheRightborder SetsthewidthoftheRightborder
Setsthecolorofthetopborder Setsthestyleofthetopborder Setsthewidthofthetopborder
Example:Settheallborderoftext <html> <head> <styletype=text/css> p { border:mediumdoublergb(250,0,255) } </style> </head> <body> <p>U.VPatelCollegeofEngineering</p> </body> </html> Output:
Example:Setthetopborderpropertyoftext <html> <head> <styletype=text/css> p { border:mediumdoublergb(250,0,255) } </style> </head> <body> <p>U.VPatelCollegeofEngineering</p> </body> </html> Output:
CSSMargin
The CSS margin properties define the space around elements. It is possible to use negative values to overlap content. The top, right, bottom, and left margin can be changed independentlyusingseparateproperties.Ashorthandmarginpropertycanalsobeusedto changeallofthemarginsatonce.
Property Value Description
margin
marginbottom
marginleft
marginright
margintop
margintop marginright marginbottom marginleft auto length % auto length % auto length % auto length %
Ashorthandpropertyforsettingthemargin propertiesinonedeclaration
Setsthebottommarginofanelement
Setstheleftmarginofanelement
Setstherightmarginofanelement
Setsthetopmarginofanelement
Example:SettheallMargin
<html> <head> <styletype=text/css> p.margin{margin:2cm4cm3cm4cm} </style> </head> <body> <p>Thisisaparagraphwithnospecifiedmargins</p> <pclass=margin>InformationTechnology</p> <p>GanpatUniversity</p> </body> </html>
Output:
Example:SettheleftMarginoftextusingpercentvalue <html> <head> <styletype=text/css> p.leftmargin { marginleft:25% } </style> </head> <body> <p><b>Subject:</b>InternetProgramming1</p> <pclass=leftmargin>InformationTechnology</p> </body> </html> Output:
CSSPadding
The CSS padding properties define the space between the element border and the element content. Negativevaluesarenotallowed. The top, right,bottom,and left padding canbechangedindependentlyusingseparateproperties.
Property Value Description
padding
paddingbottom paddingleft paddingright paddingtop
paddingtop paddingright paddingbottom paddingleft length % length % length % length %
Ashorthandpropertyforsettingallofthepadding propertiesinonedeclaration
Setsthebottompaddingofanelement Setstheleftpaddingofanelement Setstherightpaddingofanelement Setsthetoppaddingofanelement
Example:Setthepaddingpropertyoftable <html> <head> <styletype=text/css> td.test1{padding:1.5cm} td.test2{padding:0.5cm2.5cm} </style> </head> <body> <tableborder=1> <tr> <tdclass=test1> StudentInformationSystem. </td> </tr> </table> <br/> <tableborder=1> <tr> <tdclass=test2> SubjectName. </td> </tr></table></body></html>
Output:
Example:Settherightpaddingusingcmvalue.
<html> <head> <styletype=text/css> td{paddingright:5cm} </style> </head> <body> <tableborder=1> <tr> <td> Thisisatablecellwitharightpadding.Thisisatablecellwith arightpadding. </td> </tr> </table> </body> </html>
Output
CSSList
TheCSSlistpropertiesallowyoutoplacethelistitemmarker,changebetweendifferentlist itemmarkers,orsetanimageasthelistitemmarker.
Property Value Description
liststyle
liststyleimage liststyleposition liststyletype
paddingtop
liststyletype liststyleposition liststyleimage none url inside outside None,disc,circle square,decimal decimalleading zero,lower roman upperroman ,loweralpha upperalpha, lowergreek lowerlatin upperlatin, hebrew ,armenian georgian cjkideographic hiragana katakana hiraganairoha katakanairoha length %
Ashorthandpropertyforsettingalloftheproperties foralistinonedeclaration Setsanimageasthelistitemmarker Setswherethelistitemmarkerisplacedinthelist Setsthetypeofthelistitemmarker
Setsthetoppaddingofanelement
Example:Setanimageasthelistitemmarker. <html> <head> <styletype=text/css> ul { liststyleimage:url(arrow.gif) }
</style> </head> <body> <ul> <li>ComputerEngineering</li> <li>InformationTechnology</li> <li>BioMedicalEngineering</li> </ul> </body> </html> Output:
CSSTable
TheCSStablepropertiesallowyoutosetthelayoutofatable.
Property Value Description
tablelayout captionside
borderspacing emptycells
auto fixed top bottom left right length show hide
Setsthealgorithmusedtodisplaythetablecells, rows,andcolumns Setsthepositionofthetablecaption
Setsthedistancethatseparatescellborders Setswhetherornottoshowemptycellsinatable
Example:Setthelayoutoftable. <html> <head> <styletype=text/css> table.one { tablelayout:automatic } table.two { tablelayout:fixed } </style> </head> <body> <tableclass=oneborder=1width=100%> <tr> <tdwidth=20%>1000000000000000000000000000</td> <tdwidth=40%>10000000</td> <tdwidth=40%>100</td> </tr> </table> <br/> <tableclass=twoborder=1width=100%> <tr> <tdwidth=20%>1000000000000000000000000000</td> <tdwidth=40%>10000000</td> <tdwidth=40%>100</td> </tr> </table> </body></html>
Output:
Example:SettheSpacebetweentableborder. html> <head> <styletype=text/css> table.one { bordercollapse:separate; borderspacing:10px } table.two { bordercollapse:separate; borderspacing:10px50px } </style> </head> <body> <tableclass=oneborder=1> <tr> <td>Peter</td> <td>Griffin</td> </tr> <tr> <td>Lois</td> <td>Griffin</td> </tr> </table> <br/> <tableclass=twoborder=1> <tr> <td>Cleveland</td> <td>Brown</td> </tr> <tr> <td>Glenn</td> <td>Quagmire</td></tr> </table></body></html>
Output:
Example:Setthepositionoftablecaption. <html> <head> <styletype=text/css> caption { captionside:bottom } </style> </head> <body> <tableborder=1> <caption>StudentInformation</caption> <tr><th>Name</th><th>RollNo</th></tr> <tr><td>Peter</td><td>IT061</td></tr> <tr><td>Lois</td><td>IT061</td></tr> </table> </body> </html> Output:
CSSDimension
TheCSSdimensionpropertiesallowyoutocontroltheheightandwidthofanelement.It alsoallowsyoutoincreasethespacebetweentwolines.
Property Value Description
height width maxheight maxwidth minheight minwidth
Auto,length,% Auto,%,length None,length,% None,length,% Length,% Length,%
Setstheheightofanelement Setsthewidthofanelement Setsthemaximumheightofanelement Setswhetherornottoshowemptycellsinatable Setstheminimumheightofanelement Setstheminimumwidthofanelement
Example:Settheheightandwidthofimageusingpixelvalue. <html> <head> <styletype=text/css> img.normal { height:auto; width:auto } img.big { height:160px; width:160px } img.small { height:30px; width:160px } </style> </head> <body> <imgclass=normalsrc=logocss.gifwidth=95height=84/> <br/> <imgclass=bigsrc=logocss.gifwidth=95height=84/> <br/> <imgclass=smallsrc=logocss.gifwidth=95height=84/> </body> </html>
Output:
CSSPseudoClasses
CSSpseudoclassesareusedtoaddspecialeffectstosomeselectors.
Syntax
Thesyntaxofpseudoclasses: Selector:pseudoclass{property:value}
AnchorPseudoclasses PseudoClass Description
Active Hover Link Visited
Addsspecialstyletoanactivatedelement Addsspecialstyletoanelementwhenyoumouse overit Addsspecialstyletoanunvisitedlink Addsspecialstyletoavisitedlink
Alinkthatisactive,visited,unvisited,orwhenyoumouseoveralinkcanallbedisplayedin differentwaysinaCSSsupportingbrowser: a:link{color:#FF0000}/*unvisitedlink*/ a:visited{color:#00FF00}/*visitedlink*/ a:hover{color:#FF00FF}/*mouseoverlink*/ a:active{color:#0000FF}/*selectedlink*/
PseudoclassesandCSSClasses
PseudoclassescanbecombinedwithCSSclasses: a.red:visited{ color:#FF0000 } <aclass=redhref=css_syntax.asp>CSSSyntax</a> Ifthelinkintheexampleabovehasbeenvisited,itwillbedisplayedinred.
Example:Exampletodemonstratedifferenthyperlinkcolor <html> <head> <styletype=text/css> a:link{color:#FF0000} a:visited{color:#00FF00}
a:hover{color:#FF00FF} a:active{color:#0000FF} </style> </head> <body> <p><b><ahref=default.asptarget=_blank>Thisisalink</a></b></p></body> </html> Output:
CSSImageOpacity
FirstwewillshowyouhowtocreateatransparentimagewithCSS. Regularimage:
The same image with transparency:
Example: <html> <head> <styletype=text/css> img { opacity:0.4; filter:alpha(opacity=40) } </style> </head> <body> <h1>ImageTransparency</h1>
<imgsrc=logo.jpgwidth=150height=113alt=klematis onmouseover=this.style.opacity=1;this.filters.alpha.opacity=100 onmouseout=this.style.opacity=0.4;this.filters.alpha.opacity=40/> </body> </html> Output: