CSS Is Your Friend

Don’t Be Afraid to Use Cascading Style Sheets

Andrew Flick

October 30, 2009

8 Min Read
ITPro Today logo in a gray background | ITPro Today

UI Tips

LANGUAGES:ALL

ASP.NETVERSIONS: ALL

 

CSS Is Your Friend

Don t Be Afraid to Use Cascading Style Sheets

 

By Andrew Flick and Devin Rader

 

Here s a question for all of you rapid application Webdevelopers: Do you find yourself setting the same properties multiple times?For instance, have you set the font or the color of a font more than once in anapplication, setting it to the exact same specifications each time? If youanswered yes to either of the preceding questions, you may be a candidate forcascading style sheets, better known as CSS.

 

CSS has been around for a long time, but we felt it was anecessary addition to our tips and tricks section because, even to this day,people are afraid of utilizing the technology. It seems that many people stillinsist on either writing the same blocks of code over and over (and over)again, or they click on different controls in Visual Studio.NET and set theexact same settings multiple times, as if CSS is some sort of voodoo. There isabsolutely nothing wrong with that; however, if you want to make anapplication-wide style change, it does make maintenance quite a pain.

 

Currently there are two separate versions of CSS inexistence: CSS1 and CSS2. All CSS1 style sheets work and are valid CSS2 stylesheets; however, CSS2 adds the capability for the designer to target differentend-devices (such as printers and handheld devices). Furthermore, according tothe W3C, CSS2 supports content positioning, downloadable fonts, table layouts,internationalization, and many more features geared for UI development. For thepurpose of this article, we ll discuss the basics of CSS1, because manydevelopers are targeting IE as their end-browser and IE does not fully supportCSS2 as, according to Microsoft Watch, Microsoft views the currentimplementation of CSS2 as flawed. Finally, CSS3 is currently underdevelopment, so it will be exciting to see if this gains traction in theMicrosoft world and acceptance of the W3C. So, utilizing CSS1, we ll discussthe structure of CSS, inline vs. external styles, CSS classes, precedence, andinheritance.

 

The Structure of CSS

Learning CSS is a rather simple process. Really all youneed to know is basic HTML and some of the terminology used by most wordprocessors, such as font, forecolor, H1, etc. The declaration of a CSS ruleconsists of a selector and a declaration:

 

selector{property:value;}

 

The selector is the HTML tag name, id, or class of theelement for which you want to define rules. You can place multiple declarationsinside each selector. For example, if you re working with the entire body of aWeb page and you want to deal with the font:

 

body

{

     font-size: 8pt;

    color: blue;

    font-family:Sans-Serif;

}

 

You re not limited to only dealing with font; you can alsoquickly modify background, lists, and how elements are positioned. There is alot of power here.

 

Inline Styles vs. External Styles

So far the style rules that we ve used can simply beplaced in the

 

 

This declaration will make all the text inside this tag bebold, gray, Arial, and underlined. The one thing you ll need to make mention ofis the fact that the style is wrapped in quotations when declared inline.

 

The second, and probably more common, way of utilizingstyle sheets is to declare them in an external file. This offers a lot of powerbecause now you can affect a large number of pages by creating a style in asingle file by simply making a reference of this file.

 

An external style sheet is a simple text file and commonlyuses the naming convention .css to designate it as a style. After creating astyle using the selector/declaration syntax and saving it to myStyle.css, youneed to link this style to each Web page that you want to inherit this style.To do so, you would use the LINK tag:

 

 

The second way of referencing a style to a page is using@import. Generally speaking, the main use for this is not in a page reference,but in creating a generalized style sheet and inheriting that into anotherstyle sheet. For example:

 

Global.css

body

{

    font-size: 8pt;

    color: blue;

    font-family:Sans-Serif;

}

 

Local.css

@import url( /Global.css );

h1{color:red;}

 

CSS Classes

CSS classes allow you to create a style and apply thatseparately for different elements that inherit that class. To use a CSS class,simply give any element that is going to inherit that class the attribute classfollowed by the class name. For instance, you may have a group of labels withthe class name validator:

 

Some Text

Some Other Text

 

These validators should all be red as apposed to thedefault black of the other labels. CSS will give you a single place to declarethese as red by making use of the CSS class. To declare a class in CSS, simplyprecursor the class name with a period and make sure the case is the samebecause these classes are case-sensitive. To make our validator text red, ourclass will look something like this:

 

.validator

{

    color: Red;

}

 

The Cascade in CSS

By this time, you know the basics of CSS. You can create astyle sheet inline, import it, or even create one externally. The real questionis: What takes precedence? The order of precedence begins with the author sstylesheet, followed by the user s stylesheets, and, lastly the default browserstyles. When a user turns off styles, they are essentially changing the orderof precedence. Furthermore, some browsers enable the user to have their ownspecific style sheet take precedence and override the Web page author s stylesheet.

 

Now we know that, as the Web page author, your style sheetwill take precedence (in most scenarios). However, you may have defined stylesin separate places, so what takes precedence there? Persistent styles or thoseembedded or inline have top priority over any other stylesheet. The preferred orexternal style sheet takes the second priority, followed by any alternate stylesheets that may have been selected by the user. Keep in mind that if analternative style sheet is selected, the preferred style is turned off;however, the persistent styles remain.

 

The next order of precedence deals with conflicting rules;again, we ask what takes precedence? If you have multiple stylesheets definedand you want a particular style to take precedence, no matter in which stylesheet it is located, simply mark the style with !important :

 

H1{font-family: Arial!important;}

 

Furthermore, the more specific a style is the more weightit has. So, a style pointing to a class will have more weight than a genericstyle. Finally, the style that is listed last will take precedence, whichalludes to why persistent styles always take precedence.

 

Inheritance

Following the rules we just learned about precedence, themore specific a style is, the more weight it has. Consider this example:

 

< body>

  

...

         ...

         < div>...

   

 

The body tag would be the parent in this relationship, theparagraph tag would be a child of the body, and the div tag would be a child ofthe paragraph. If the body tag is defined to have the style of blue text, thenall the children inside the body tag will inherit blue text. However, if theparagraph tag has a style of red text, then all its children will then inheritred text. Finally, if the div tag has underlined text, then everything in thediv tag will have underlined text.

 

Conclusion

This article barely scratches the surface of CSS. Some ofthe ideas we ve discussed could be written about in much greater detail.However, this article would then become a book. For more information on CSS,head over to the W3C Web site (http://www.w3.org/Style/CSS/);they have just about everything you would ever want to know on the subject.

 

In conclusion, we touched upon the structure of a CSSstyle sheet, inline vs. external styles, CSS classes, precedence, andinheritance. For all of you who still think CSS is voodoo, we stronglyrecommend you give it a try; we think you ll soon realize the full power it hasto offer.

 

With that, we remind you to e-mail your questions to us [email protected].

 

Andrew Flick is Product Manager of NetAdvantage Windows FormsTechnologies & TestAdvantage for Infragistics, Inc., a Microsoft VisualStudio Industry Partner. He is responsible for spearheading product managementand strategies of Infragistics Windows Forms product line - working directlywith the Director of Development to set the direction, plan, and manage productdevelopment. Andrew is a Microsoft .NET MVP and is the chair of the INETAAcademic Student Committee. Contact Andrew at mailto:[email protected].

 

Devin Rader is an Infragistics TechnologyEvangelist and is responsible for authoring Infragistics reference applicationsand .NET technology articles, as well as the world-wide delivery ofInfragistics technology demonstrations. Devin is an active member andleader for INETA, has served as the sole technical editor for numerous works,and is a contributing author for the soon to be published ASP.NET 2.0Professional. Contact Devin at mailto:[email protected].

 

 

 

 

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like