Understanding CSS


Cascading Style Sheets (CSS) is a technology for defining layout or formatting for documents. Although not an XML technology, it is most useful when used in combination with XHTML, and, therefore, it is included here. CSS separates the style information from the actual content. In addition, CSS can save you time when generating pages. Rather than add font, color, or other styling information on every tag of a particular group (for example, making each h1 tag red and Arial), you apply the CSS style information to a selector and then add that selector to the elements you want formatted that way. That is, rather than sprinkling <font face=“Arial, Helvetica, sans serif” size=“3” color=“red”>Some text</font> throughout your Web pages, you add something like <span class=“emphasis”>Some text</span>. The emphasis style is defined elsewhere in one spot. Should the appearance of your emphasis text need changing, you no longer need to search through all your documents looking for items to change. Finally, CSS can save bandwidth. By having all your documents refer to the same file(s) containing style information, you save the bandwidth that would be used if this information were scattered throughout your documents. One upcoming benefit of CSS is that you will be able to apply different CSS files based on the desired output (for example, screen vs. printer) for your page.

Basics of CSS

CSS could easily fill a book, such as Wrox Professional CSS: Cascading Style Sheets for Web Design, ISBN: 0-7645-8833-8 (http://www.wrox.com/WileyCDA/WroxTitle/productCd-0764588338.html). Now, however, I'll cover only the basics and let you refer to other material as needed.

Two active levels of CSS exist: CSS 1 (originally ratified in 1996) and CSS 2.1 (as of this writing still a Working Draft that expands on CSS 2.0, originally ratified in 1998). CSS 3.0 is currently a standard in progress; it adds a number of properties that will be useful, such as column layout. However, because it will likely be some time before these properties will be supported by most browsers, I won't cover them here. If you want your CSS to work in the broadest range of browsers, you should stick with CSS 1.0. Some of the CSS 2.0 and 2.1 features are either unsupported or supported using nonstandard extensions in the various browsers.

CSS consists of a number of properties that can be applied to areas on a page. These properties have values that affect how they are rendered, and include such items as color, margins, padding, and text formatting. The following table lists some of the more commonly used properties. Note: This is hardly a comprehensive list; see Professional CSS (ISBN: 0-7645-8833-8) for more details.

Open table as spreadsheet

Property

Description

border

Sets a border around an item. Also border-left, border-top, border-right, and border-bottom set each border individually. Value is a three-part string of style line-width color. Style determines how the line is drawn (for example, solid, dashed, dotted). Line-width can be an actual length (with units) or one designated thin, medium, or thick. Color can be a named color or the RGB value (with a # preceding it). Each of these properties can also be individually enhanced with its own properties, such as border-right-style, border-top-color, and border-left-width.

margin

Sets the margin around the item. This differs from padding in that padding sets the margin between the edge of the item and the content itself. Margins sets the margin between the edge of the item and its container. You can also use margin-left, margin-top, margin-right, and margin-bottom to set each margin individually. Value is an actual length (with units) or a percentage of available space (ending with %)

padding

Sets the spacing around the content of the item. This differs from margin in that margin sets the spacing around the entire item, whereas padding adds spacing between the item's edge, and the content. You can also use padding-top, padding-right, padding-bottom, and padding-left to set each side individually. Value is an actual length (with units) or a percentage of the available space (ending with %).

color background-color

Sets the foreground or background color of an item. Value is either a named color or the RGB value (with a # preceding it). Although not absolutely necessary, if you set one of these, you should set the other as well.

background

Sets a number of the properties of the background, including color, image, and how the image interacts with the page. The value is a five-part string containing the color, image url, the repeat settings for the image, whether the image is fixed or whether it scrolls as the user scrolls the page, and the position of the image. Each of these properties can be set individually as well with the background-color, background-image, background-repeat, background-attachment, and background-position properties.

display

Sets how the item is displayed. The most common example of this is display:none, which hides the content (that is, nothing is created on the page for it). However, a number of options exist for this property, including block, inline-block, inline, and list-item.

text-align

Sets how the text is aligned within the borders of the item.

text-decoration

Adds decoration to the item. The decoration consists of underlining, overlining, blinking and striking through the item.

font-style

Sets the text as italic or oblique (angled like italics, but the other way).

font

Sets all the font properties for an item. Value is a five-part string containing the setting for the style (currently normal, italic, or oblique), variant (currently the only option is small-caps), weight (boldness), size (either a specific size, or a name that describes the size, for example: xx-small, larger), and font family (for example, Arial). Alternatively, but more rarely, the value can be the name of a system font (for example, caption, message-box, menu). Each of the properties can be set individually as well, such as font-family, font-style, font-weight, and font-size.

list-style

Sets how each list item is displayed. Value is a three-part string containing the symbol type to use as a bullet (for example, disc, square, or none), an optional URL to an image to use for the bullets, and the position of the bullet relative to the item. Each of these properties can be set individually as well, with the list-style-image, list-style-position, and list-style-type properties.

height width min-height min-width max-height max-width

Sets the size of items. Value is either an actual size (with units) or a percentage of the available space (ending with ‘%’). The min- and max-versions control the minimum and maximum dimensions of an item if the browser window is resized. They are not supported by Internet Explorer (up to version 6.0).

float

Removes an item from the normal flow of items on a page and moves it to either the left or right of the screen. Other content flows around this item. See an explanation of multicolumn layout with CSS (in the following section) for one common use of this property.

position

Changes how the item is positioned on the page. Values include static (normal behavior), relative, fixed, and absolute. With relative or absolute, you should also include left and top properties in the selector. When using relative, these values are used to adjust the position of the item relative to where it should appear in the flow of the page. When you use absolute, these values enable you to place the item exactly.

cursor

Sets the mouse pointer when the cursor is placed over it. Value is one of the standard shapes for a mouse pointer (crosshair, wait, move, default, help) or an URL pointing to a custom cursor.

overflow

Sets the behavior used if the content is larger than the assigned size. Values include visible (meaning the content continues beyond the assigned size), hidden (meaning the content is cut off at the margin), scroll (meaning the content is cut off at the margin but a scroll bar is added to view the remaining content) and auto (implementation-dependant behavior). This property can be a useful property when adding a large block of content to a page, such as when adding code samples. You can fix the size of the content and add a scroll bar if the size is larger than the requested space.

You group these properties in selectors. Each selector is applied to one of the following types of items:

  • q All elements of a named type, for example: h1 {color: red;}

  • q All elements with a particular id or all elements of one type with a particular id, for example: #doc-body {font-size:0.78em;} or h1#headline {color: red;}

  • q All elements with a particular class attribute or all elements of one type with a particular class attribute, for example: .emphasis {font-weight: bold;color:navy;} or div.fineprint {font-size: xx-small;}

  • q All elements that are contained by another element (descendant selectors), for example div a {text-decoration: none;}. This would be when one tag is contained within another tag, such as <div><a></a></div>. The a element descends from the div element. A elements not within div elements would not be affected.

  • q All elements adjacent to one another (adjacent sibling selectors), for example h1+div {margin-top: 1.5em;}. This would be when one tag immediately follows another; in this case a div immediately follows an h1 tag. Adjacent sibling selectors are not frequently encountered, but can provide a powerful formatting tool for some documents.

  • q All elements with a particular attribute or all elements of one type with a particular attribute, for example: h1[title] {font-size:2.2em; color:navy;}.

  • q Specific "pseudo" classes and elements. Certain tags, most notably the a tag, support pseudo-classes to identify specific states for the anchor. These include hover, active, link, visited. Each of these classes can have CSS applied to them for styling. In addition, elements support the lang class to style different languages. Some clients also support pseudo-elements such as before, first-line, first-letter and more. Consult a CSS reference for the complete list of pseudo-elements and selectors, but be aware that many of these have poor support by some browsers.

Listing 3-7 shows examples of these three types of selectors. Selectors are made up of one or more named items and the properties associated with those items surrounded by braces ({}).

Listing 3-7: CSS selectors

image from book
      body {        margin: 0;       padding: 0;       border: 0;       text-align: center;       color: #554;       background: #692 url(images/background.gif) top center repeat-y;       font: small tahoma, "Bitstream Vera Sans", "Trebuchet MS",        "Lucida Grande", lucida, helvetica, sans-serif;       }      #main {       width: 400px;       float: left;       }      #sidebar ul li {             list-style: disc url(images/bullet.gif) inside;       vertical-align: top;       padding: 0;       margin: 0;       }      .content-body {        line-height: 140%;        }      h3.content-title {       margin-top: 5px;       font-size: medium;       } 
image from book

The sample CSS in Listing 03-7 includes five selectors. The first is associated with the body tag of the page, but you create element-associated selectors using this format. The selector sets the margins, padding, and border to 0, meaning the content will appear flush with the edges of the browser window. The background property sets the color and assigns an image for the background. The image is set to the top of the page, and it repeats down the page. If the browser window is too wide, the graphic is not repeated.

The second and third selectors show the id form of naming a selector. The first creates a named selector called main. Any tag that includes the attribute id=“main” has this selector associated with it, setting the width and floating it to the left margin. The second form of the id selector is applied to all li tags that are within a ul element that is within an area marked with the id=“sidebar” attribute. This form of the selector is very useful in blocking off sections of your page. For example, you might break down your page into navigation, main, sidebar, and footer sections to define areas of the page, and then create selectors that include that information. This causes tags to appear differently depending on their location on the page.

      <div >        <h2>List Title</h2>        <ul>          <li><a href='http://www.example.com/someLink'>Item 1</a></li>          <li><a href='http://www.example.com/someOtherLink'>Item 2</a></li>        </ul>      </div> 

The fourth and fifth selectors show the class form of naming a selector. The first creates a selector called content-body. Any tag that has the attribute class=“content-body” has this selector applied to it, setting the line height to 140% of normal. The second form applies only to h3 tags with a class of content-title. This form of the tag is useful as a means of precisely formatting a block of content. In addition, if you had multiple h3 tags, you could format some of them by including the class attribute.

You can include selectors either directly within the file or as an external file. When adding style information directly to the page, you should identify the style block as CSS and provide an id for reference (see Listing 3-8). In addition, if your styles include any characters significant to XML, such as < and &, you should wrap them in a CDATA block.

Listing 3-8: Style information in an XHTML document

image from book
            <?xml-stylesheet href="#internalStyle" type="text/css"?>      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">      <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">        <head>          <title>Title</title>          <style type="text/css" >            <![CDATA[              body {                margin: 0;                padding: 0;                border: 0;                text-align: center;                color: #554;                background: #692 url(images/background.gif)                  top center repeat-y;                font: small tahoma, "Bitstream Vera Sans", "Trebuchet MS",                  "Lucida Grande", lucida, helvetica, sans-serif;              }              #main {                width: 400px;                float: left;              }              #sidebar ul li {                list-style: disc url(images/bullet.gif) inside;                vertical-align: top;                padding: 0;                margin: 0;              }              .content-body {                line-height: 140%;              }              h3.content-title {                margin-top: 5px;                font-size: medium;              }            ]]>          </style>        </head>        <body>          <div >            <h3 >Some Title</h3>            <div >Lorem ipsum dolor sit amet,              consectetuer adipiscing elit.</div>          </div>          <div >                  <h2>List Title</h2>            <ul>              <li><a href='http://www.example.com/someLink'>Item 1</a></li>              <li><a href='http://www.example.com/someOtherLink'>Item 2</a></li>            </ul>          </div>        </body>      </html> 
image from book

Because of the issues around the & and < characters, it is generally best to include CSS information in external files and reference them in your pages. In addition, including the CSS information in a separate file means that the file needs to be downloaded only once, reducing bandwidth requirements. The two ways of including an external style sheet with a document are the XML way and the HTML way. You can use either method, although the XML way is preferred.

The XML way of including an external CSS reference is to use a processing instruction (see Listing 3-9). The xml-stylesheet processing instruction takes the URL of the CSS file and identifies it as the MIME type text/css.

Listing 3-9: An external CSS reference using processing instructions

image from book
      <?xml version="1.0" encoding="utf-8" ?>      <?xml-stylesheet href="sample.css" type="text/css"?>      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">      <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">        <head>          <title>External CSS Reference using PI</title>        </head>        <body>          ...        </body>      </html> 
image from book

The HTML way of including an external CSS reference, shown in Listing 3-10, still works with XHTML. This method uses a link element. The link includes the URL of the CSS, the MIME type, and an identification of it as the stylesheet using the rel attribute.

Listing 3-10: An external CSS reference using the link element

image from book
      <?xml version="1.0" encoding="utf-8" ?>      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">      <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">        <head>          <title>External CSS Reference using PI</title>          <link href="sample.css" type="text/css" rel="stylesheet" />        </head>        <body>          ...        </body>      </html> 
image from book

By this point, I would expect you are more than a little curious about where the Cascading part of the name comes from. The name comes from the way CSS is applied to an item when multiple selectors apply and when multiple sources of CSS are included in a document. CSS selectors cascade or flow from more local to more general. That is, selectors deemed more important take precedence. The rules governing the application of CSS in these situations are basically as follows:

  1. If only a single selector applies to the item, that selector is applied.

  2. If two or more selectors apply to an item and they do not conflict, both are applied. That is, they "cascade" together.

  3. If two or more selectors apply to an item, and one or more properties conflict, the more specific property is applied. Therefore, if you had a generic h2 selector, and h2 class=“foo” to apply to an item, the properties of h2 class=“foo” would override the conflicting value in the generic h2 selector.

  4. If a property is assigned to an item in both an external and internal stylesheet, the properties of the internal (more local) stylesheet are applied.

CSS Examples

In addition to simply applying a few styles to a document, CSS is frequently used to perform certain tasks. For example, although many people create their overall page layout with a mixture of tables, they could create a multicolumn layout very simply using CSS. In addition, because you can easily change the CSS for your pages, why not allow your users to select their personal favorites?

Box Layout and Cross-Browser Compatibility

Although Internet Explorer was the first browser to support CSS, even before it was a standard, Explorer has fallen a little behind the standard. Some aspects of CSS 2 are currently unsupported, and even some areas of CSS 1.x are implemented differently in Internet Explorer than in other browsers (or the standards). The most significant of these is the Box model (see Figure 3-8). The Box Model is the way that the margins, padding, and borders are constructed around a piece of content.

image from book
Figure 3-8

Older versions (4.0–5.5) of Internet Explorer are notorious for interpreting the Box Model incorrectly. Figure 3-9 shows this in action, with Internet Explorer 5.0 depicted in the top version, and Firefox 1.5 in the lower. The red line beneath the two grey boxes represents 300 pixels, whereas the green shows 344 pixels. The content box width is set by the combination of the width, margin, border, and padding. In versions of Internet Explorer before 6.0, width meant the total width of all these values. Therefore, adding margin, padding, and border made the text area narrower. Internet Explorer 6.0, Firefox, and Opera interpret the width correctly, adding margin, padding, and border to the outside of the width value. This leads to the total width of 344 pixels. The page with its CSS is shown in Listing 3-11.

image from book
Figure 3-9

Listing 3-11: Box Model differences between browsers

image from book
      Page:      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">      <html xmlns="http://www.w3.org/1999/xhtml" >      <head>          <title>Box Model</title>                <link href="BoxModel.css" rel="stylesheet" type="text/css" />      </head>      <body>      <div >Lorem ipsum dolor sit amet,      consectetuer adipiscing elit. Suspendisse sit amet odio.      Duis porta pulvinar arcu. Curabitur pellentesque,      neque id hendrerit volutpat,      ante nulla mattis lacus, sit amet varius augue orci a enim. </div>      <div >&nbsp;</div>      <div >&nbsp;</div>      </body>      </html>      CSS:      div.border      {          border: solid 2px black;          padding:20px;          width: 300px;          background-color: #ccc;      }      div.rulerIE      {          width:300px;          background-color: Red;      }      div.rulerCSS      {          width: 344px;          background-color: Green;      } 
image from book

Solving the Box Model problem with older versions of IE is a bit of a cottage industry: a number of solutions have been proposed. Most involve adding extra information to the CSS file. This information is ignored by most browsers but interpreted by earlier versions of IE. Some of the more popular ones include:

  • q The Box Model Hack: First proposed by Tantek Çelik of Technorati, this method involves adding a second selector with a false ending. In the following code, the second div.border selector overrides the width set in the first. The odd looking line "voice-family: “\”}\“”;" uses the rarely set voice-family property. Most browsers ignore this line because it is not valid. However, versions of Internet Explorer (5.5 and earlier) interpret it as, "voice-family:}". That is, IE 5.5 and earlier see this line as the end of the selector and ignore the next two lines. Other browsers ignore this line, and interpret the following two lines, setting the width as appropriate and resetting the voice-family to the default.

          div.border      {          border: solid 2px black;                padding:20px;          background-color: #ccc;          width: 300px;      }      div.border {        width:344px;        voice-family: "\"}\"";        voice-family:inherit;        width:300px;      } 
  • q The Simplified Box Model Hack: First proposed by Andrew Clover, this method leverages the string escape method of CSS to include multiple copies of the width. CSS-aware browsers read the correct value, whereas browsers that improperly handle the escapes have the value overridden later in the file.

          div.border      {          border: solid 2px black;          padding:20px;          background-color: #ccc;          width: 300px;      }      div.border      {          \width: 344px;          w\idth: 300px;      } 
  • q The Modified Simple Box Model Hack: This method, also known as the Star HTML Hack, was proposed by Edwardson Tan and includes a selector for the invalid * html before the desired tag. This, like the other hacks, is ignored as invalid by browsers such as Firefox or Opera and processed by older versions of Internet Explorer (5.5 or earlier).

          div.border      {          border: solid 2px black;          padding:20px;          width: 300px;          background-color: #ccc;      }      * html div.border      {          width: 344px;      } 

One or all these hacks will likely work for you. Personally, I've found the Simplified Box Model Hack works quite well, and it is simple enough to implement. In general, you should include these hacks in separate CSS files, and use import statements to include them in your normal CSS. That way, you need to change only one line to remove them when you no longer need the hack.

Multicolumn Layout with CSS

Most, if not all, Web sites involve multiple column layouts. The content itself may be in multiple columns, or columns may be used for navigation or other page elements. The classic method of laying out a page like this is to use a combination of tables and 1-pixel transparent graphics to position items on the page. As you can imagine, this technique has a number of problems-it can be difficult to manage, particularly if you've got nested tables. All those tags bulk up the document, increasing download times; and this technique is definitely not accessible to those who read the page using screen readers or similar technologies. Because of this, it's a good idea to replace these pages with CSS to create the multiple column layout. However, doing so has its own problems, most notably browser compatibility with some of the CCS techniques. Even if you ignore older browsers (pre-Internet Explorer 4 or Netscape Navigator 3) that do not support CSS, a few compatibility issues still exist because each browser tends to interpret the CSS standards differently. Some comply only with CSS 1.x, whereas others are compatible CSS 2.x. As with any CSS technique, it is a good idea to validate your pages and to view them in a variety of browsers and platforms to ensure your pages work properly.

Figure 3-10 shows a simple two-column layout using CSS. As you can see, the left Menu Area does not change in size as the browser window is increased. Instead, the main content area expands and contracts to fit the available space. This is the simplest way of creating a page layout with a banner, left navigation area, and main area.

image from book
Figure 3-10

Creating this two column layout is a simple matter. The CSS and HTML used are shown in Listing 3-12. The only important selectors are the two highlighted ones setting the width of the menu area, and float:left. The float selector causes the area to be removed from the normal processing of the page and positioned at the left margin. Remaining content wraps around this area, so if the main content area's content is longer than the menu area (which it likely will be); you should adjust the padding-bottom to prevent this.

Listing 3-12: Two column layout with CSS

image from book
      CSS:      body      {          background-color: #0000cc;          color:#000;      }      #banner      {          background-color:#00cc00;          color:#000;          padding:20px;          border: solid 1px #000;      }      #leftColumn      {          float:left;          width:300px;          background-color:#fff;          color:#000;          border: solid 1px #000;          padding-left: 20px;          padding-right:20px;          padding-bottom:200px;      }      #mainContent      {          background-color: #ccc;          color:#000;          border: solid 1px #000;      }      XHTML:      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">      <html xmlns="http://www.w3.org/1999/xhtml">      <head>          <title>Two Column Layout</title>          <link href="TwoColumn.css" rel="stylesheet" type="text/css" />      </head>      <body>          <div >Banner Area</div>          <div >              <h3>Menu area</h3>                    <div>                  Lorem</div>              <div>                  ipsum</div>              <div>                  dolor</div>          </div>          <div >              <h3>Main Content Area</h3>              <div>                  Lorem ipsum dolor sit amet, consectetuer adipiscing elit.                  Suspendisse sit amet odio.                  Duis porta pulvinar arcu. Curabitur pellentesque, neque id                  hendrerit volutpat, ante                  nulla mattis lacus, sit amet varius augue orci a enim.</div>          </div>      </body>      </html> 
image from book

Validating CSS

Just as with XHTML, it is best if you validate your CSS before releasing it into the wild. You have at least two main means of validating your CSS. First, you should run your style sheets through a mechanical validator, such as the online one at http://www.jigsaw.w3.org/css-validator. This identifies any major errors you may have, as well as shows you any items that aren't covered in the version of the standard you are targeting.

The second and much more important means of validating your CSS is to look at the resulting page in as many browsers as you think may be used to view your site. Generally, this means Internet Explorer, Netscape Navigator, Firefox, Opera, and any others that appear regularly in your Web server logs. In addition, you probably want to use multiple versions of those programs, and probably also some versions running on multiple platforms. Using virtualization software, such as Microsoft Virtual PC or VMWare, makes it easy to keep all these versions available when you need to test a page.




Professional XML
Professional XML (Programmer to Programmer)
ISBN: 0471777773
EAN: 2147483647
Year: 2004
Pages: 215

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net