CSS (Cascading Style Sheets) An Overview by Michael Masumoto date: 04/25/1999 email: michael@michaelmasumoto.com phone: 707-869-1205 Introduction: Ever since the advent of HTML, designers have cried out for better control over the look and feel of their Web pages. Now, with the introduction of Cascading Style Sheets (CSS), a much greater degree of control over the look and feel of a Web site is possible. The World Wide Web Consortium, or W3C, is the international standards organization established in 1994 to help shape the development of the Web. Netscape Communications and Microsoft, among with many others, are both members of the W3C. The W3C has established guidelines for Cascading Style Sheets, which can be accessed at: http://www.w3.org The W3C guidelines for CSS are the best source for a comprehensive and current list of style properties and information. Not all of the W3C recommendations have been implemented, however. To find out the latest on what works and what doesn't, refer to Webreview.com, which has a easy-to-follow review of all CSS properties and their state of implementation on each browser and platform. http://www.webreview.com An excellent and comprehensive reference to CSS and Dynamic HTML is Danny Goodman's work, "Dynamic HTML: The Definitive Reference", O'Reilly and Associates, publishers, ISBN: 1-56592-494-0. Cascading Style Sheets are NOT a stable or completely developed technology. At the time of this writing (early 1999), style sheets suffer from an inconsistent and incomplete implementation of the W3C CSS1, CSS-P, and CSS2 guidelines. Web developers are cautioned to proceed at their own risk when using style sheets. Remember to test pages using style sheets on both Netscape Communicator and Microsoft Internet Explorer to confirm that pages will display correctly. Basic Concepts The idea behind cascading style sheets is a simple one. Instead of always having to program the look and feel of a Web site into each HTML document individually (which takes a great deal of time and effort, especially when changes are required), wouldn't it be great to have some way of defining the way the Web pages for a site should look IN AN EXTERNAL DOCUMENT? If you had all the styles for a Web site defined in a single external document, you could avoid the complications of having to program and change individual Web pages (a laborious process at best) by applying those externally defined parameters (or "styles" as they are known in publishing jargon) to ALL the pages in a Web site. Then, when a change is made to the look of a Web site, ALL the pages affected by that external "style sheet" would be automatically updated. Cool, huh? And new pages would automatically assume the look and feel of all the rest of the pages in the Web site because they, too, would have their look and feel determined by this external style sheet. But wait, there's more. Because the content of the Web site is independent from the formatting, you could repurpose the content of the Web site, or redesign the Web site, very easily. All you would have to do is assign a new style sheet to the extant HTML pages, and suddenly everything would look fresh and different. This sort of feature is very handy in a world where graphic designers and content providers are constantly tweaking, revising or updating a company's Web site materials, and in situations where portions of stable content need to be repurposed to another Web site. In the past, the Web programmer would have to rework, redesign and reimplement the Web site every time a sweeping change was made, which was costly and time-consuming. Style sheets make Web site development much more flexible, since programmers no longer have to reprogram a multitude of Web pages every time the background tile is altered or the company's logo, colors and layout change. Cascading Style Sheets also give the Web designer a very fine control over a Web page's font styles and sizes, over the margin widths, over the alignment, the line spacing, the borders, the backgrounds. The amount of control possible over a Web page's layout with style sheets far exceeds anything possible with ordinary HTML. Almost anything that you can control in a word processing program, you can now control in a Web page using Cascading Style Sheets. Of course, you pay for this power with a great deal of programming. If you really want to control the look and feel of your Web pages as you would control a Microsoft Word document, for instance, you're going to have to define a lot of elements and properties. Basic Style Sheet Syntax Style sheets are just a list of properties (margin-width, border, font-size, etc.) which are used to define various HTML tags (BODY, P, B, H1, etc). Every HTML tag can be defined in whatever manner you, as the Web programmer, decide. You could decide, for instance, to define the tag as causing text to turn italicized, 48 pt and green, and not become bold at all (although this is obviously not recommended). Style sheet-defined tags will override the default browser tag definitions. Conversely, any tags that remain undefined will default to the browser default definitions. A. Properties Style sheet properties are divided into two parts: selector and value. The selector is the name of the property (i.e., font-size, margin-width, etc.). The value is represented by various units, depending on the type of selector chosen (if the selector is font size, for instance, the value might be "18pt" or "large" or some other appropriate value). Remember: Not all properties listed in the W3C guidelines have been implemented, and those properties that have been implemented have not necessarily been implemented consistently from browser to browser; test every selector and every value you plan to use on both Microsoft and Netscape browsers. Properties are indicated in this manner, separated by a colon: selector: value Defining HTML Tags Using Properties: Properties are used to define HTML tags in a style sheet. Here's how the syntax looks: TAG { selector: value } First you have the type of tag (i.e., P, BODY or H1), then the opening curly-bracket, then the property (consisting of a selector and a value separated by a colon, i.e., "font-size: 14pt") and lastly the closing curly-bracket. The use of spaces to separate elements is flexible, and is at the discretion of the programmer. When using multiple properties to define an HTML tag, separate the properties with semicolons (you may use as many properties as you like): TAG { selector1: value1; selector2: value2; selector3: value3; selectorN: valueN } Here is an example of a tag defined by a single property: P { font-size: 18pt } The above example sets all instances of the
tag to display text at a font size of 18 points. Here is an example of a tag defined by multiple properties: P { font-size: 18pt; color: green; text-align: right } The above example sets all instances of the
tag to display text with a green color, with a font size of 18 points, and with the text aligned right. B. Comments Comments are little statements inserted into a block of code that say something about the purpose of that section of code. In HTML, comments are generally used two ways: 1) to block confusing pieces of code from certain types of browsers; 2) to make statements or comments about various things, to clarify the programmer's intent or to provide additional, helpful information on the purpose of the code. HTML comments are marked like this: Comments in style sheets are indicated differently. C or C++ style comments are the norm in style sheet syntax. Here are two examples: // Two slashes mark a single line of comment. /* Multiple lines of comment can be indicated with a slash-asterisk at the beginning, and an asterisk-slash at the end. This comment could run paragraphs or lines without end before coming to some sort of conclusion... It is at my discretion. This is the recommended form of comment for style sheets. Here's the end of the comment: */ Only use the double-slash form of comment under very specialized circumstances; double-slash comments behave unpredictably. In general, the multiple line, slash-asterisk form of commenting is the only one used. Basic Style Sheet: Here is a very basic style sheet: /* Style Sheet -- myStyle1.css Michael Masumoto -- michael@michaelmasumoto.com */ P { font-size: 18pt } H1 { font-size: 36pt; font-weight: bold } In this style sheet, we have: 1) started with a comment, declaring the name of the style sheet and the name of the programmer who created the style sheet, along with contact information (this is not required, it is just considered good programming form). 2) defined the
tag to display text at 18 points. 3) defined the tag to display text at 36 points and bold. Again, any tags that have not been defined in a style sheet will automatically default to the Web browser default values. C. Contextual Selectors You can also define how a tag will format something when it is contained within the boundaries of another tag (that is to say, when one tag is the "child" to another, "parent" tag). This is called a "contextual selector," and this is how it should look: P B { color: pink; font-weight: bold } This example sets all instances of the tag which appear within the boundaries of a tag to cause text to appear both bold and pink. In other words, when the tag is the CHILD of the tag, it will cause text to display both bold and pink. tags that are NOT used within the boundaries of a tag (in other words, are not CHILDREN of the tag) remain unaffected. Using these "contextual selectors," you can define how certain tags will display under many different conditions. For instance, you could define theHere is a green paragraph.The following bold text would also display green.
In the above example, the tag is a "child" of the tag, which is a "child" of the tag. Only the tag has inline style sheet information, yet both the and the tags INHERIT that style information from the parent tag, causing their text to display with a green color. With style sheets, some properties are inheritable, and others are not. "Color", obviously, is inheritable, as is "font-size", among others. Please refer to the W3C CSS specifications for a complete listing. B. CLASS and ID In a style sheet, you define the properties of many HTML tags. Quite frequently, however, you will require variations on one or more of the styles that you have defined. To allow for these possible variations in style definitions for individual HTML tags, classes and IDs were developed. Class is an object-oriented programming term that has migrated into style sheet terminology. In style sheets, a class is a specifically defined variation on a style (as in, "mySpecialDefinition is a CLASS of thetag"). Let's look at an example to clarify this statement. Say you have set your
tag to display black text. Throughout your document, however, you have a special WARNING type of paragraph that you want to display using RED text instead of black. Now, you could use an inline style sheet to make each WARNING paragraph display with red text, but if you ever wanted to change the appearance of the WARNING paragraphs (say by making them display 24pt text in addition to the red color), you would have to go back and change each one of the inline style sheets individually to reflect that change (yuck!). Obviously, this is not an efficient method. Instead of using inline style sheets, you could define a "warning" class of paragraph in your linked style sheet. Your regular paragraphs could be set to display 14pt black text (for instance), while your warning paragraphs could be set to display 24pt red text using this special "warning" class that you have defined. That way, if any additional changes were to be made to the appearance of the warning paragraphs, all you, as a programmer, would have to do would be to change the definition of the "warning" class for the tag in your linked style sheet, and every instance of the warning paragraph in your HTML documents would be updated. How is this done? First, you have to define the "warning" class in your external style sheet. Here's an example: /* Here's the definition for the regulartag. */ P { color: black; font-size: 14pt } /* Here's the definition for the warning class of the
tag. */ P.warning { color: red; font-size: 24pt } Now, in your HTML documents (which are, of course, linked to your external style sheet), you need to use the CLASS attribute and place it within the appropriate tags, set to "warning" (the name of your class). Here's an example of text:
My first paragraph of text is perfectly ordinary. There is nothing unusual about it at all. It is rather boring, actually. It just goes on and on for the purposes of demonstration.
Now, here is my special warning paragraph. It will display in a bigger font and become red because that is how I have defined it in my linked style sheet. Yippee!
You can also use multiple class definitions for the same tag, as shown below: /* Here's the definition for the regulartag. */ P { color: black; font-size: 14pt } /* Here's the definition for the warning class of the
tag. */ P.warning { color: red; font-size: 24pt } /* Here's the definition for the caution class of the
tag. */ p.caution { color: yellow; font-size: 18pt } Just as you did with the "warning" class of paragraph, you could now refer to this new "caution" class of paragraph using the CLASS attribute in your
tag, as demonstrated below:Now, here is my special warning paragraph. It will display in a bigger font and become red because that is how I have defined it in my linked style sheet. Yippee!
This paragraph will display at 18pt with yellow text because I have defined it as an instance of the "caution" class of paragraph.
In addition to creating specific classes of particular tags, you can also create blanket classes that will affect EVERY tag. You do this by dropping the tag name in front of the class selector. To use our example from above, you could drop the tag name from in front of ".warning". This "warning" class could be applied to every HTML tag, and would read as follows: /* Here we define a class for every HTML tag affected by this style sheet.*/ .warning { color: red; font-size: 24pt } Remember: In style sheet terminology, the "." character indicates CLASS. As a general rule, the CLASS attribute can be used in ANY HTML tag to refer to a class definition in your style sheet. In other words, the CLASS attribute, as a whole, is available as an attribute for any and all HTML tags. An ID is one step more specific than a class, and will override a class definition when the two come into conflict. In all other respects, an ID is very similar to a class, EXCEPT for the fact that each ID that you define refers to one and only ONE unique object on a page. IDs are mostly used in CSS-P and Dynamic HTML. In a style sheet, IDs are referred to by their given name, preceded by a # symbol. Here is an example: /* Here is the banana ID style. */ #banana { color: yellow } You would apply this "banana" ID to any HTML tag in your HTML document using the ID attribute, as follows:Chiquita Banana is the thing for you, it's yellow and tasty and fun to chew.
Note: Quotation marks around the values for the CLASS and ID attributes are not required. You could legally state classes and IDs using the following syntax in your HTML documents:Now, here is my special warning paragraph. It will display in a bigger font and become red because that is how I have defined it in my linked style sheet. Yippee!
This text has a banana in it.This paragraph of text is ordinary. See how it uses the standard purple color.
This paragraph of text is assigned to the "warning" class. Notice how it uses the red color appropriate for that class.
Example: "document2.html"This paragraph of text is formatted using the embedded-style-sheet-defined blue text. We've overriden the linked style sheet's purple text color with the embedded style sheet.
This paragraph of text is assigned to the "warning" class. Uh oh. In Internet Explorer, this paragraph turns blue, but in Netscape Communicator, this paragraph becomes red. Wouldn't it be most logical to have it become red, since we've assigned the paragraph to the "warning" class?
The above example uses just text color to make its point, but ALL style properties would be affected in the same manner in this conflict between Netscape's and Microsoft's interpretation of cascade conflict resolution in regards to embedded style sheets. A workaround for this conflict is to RESTATE every class and ID definition you might use within the embedded style sheets you place into HTML documents. This could get very cumbersome, however, in the event of changes to your class and ID definitions. If you plan to use classes and IDs in your style sheets, it is probably best to AVOID embedded style sheets entirely, if you can manage to do so. There are certainly more inconsistencies between Microsoft and Netscape browsers regarding cascade conflict resolution (and many other things) than the ones I have mentioned above. Remember to test everything that you are planning in regards to style sheets on BOTH browsers, and to make CONSERVATIVE plans. Until cascading style sheets stabilize as a technology, there will be any number of inconsistencies and problems which you, as a web designer and programmer, will have to work around. Units of Measurement Each style sheet property has its own list of potential values. However, when units of measurement are called for, there are three types: relative, percentage, and absolute. Relative Units: em: The height of the element's font (example: "0.5em") ex: The height of the lowercase letter "x" (example: "1.25ex") px: Pixels, relative to the "canvas" (usually, as viewed on a user's monitor) (example: "24px") Percentage Units: %: Percent (example: "50%") Percentage units can be either positive or negative (default is positive). When needed, use either a "+" sign (for positive) or a "-" sign (for negative). Place this indicator immediately before the numerical value. Example: "-25%", "50%" Absolute Units: in: Inches (example: ".5in") cm: Centimeters (example: "1cm") mm: Millimeters (example: "12mm") pt: Points (1pt = 1/72 inch) (example: "24pt") pc: Pica (1pc = 12pt) (example: "3pc") Remember: When using these units of measurement in style sheets, make certain NOT to put a space between the number and the abbreviation representing the type of unit involved. For instance, DON'T use "12 pt", but DO use "12pt". Units of Color When defining color in style sheets, you may use either hexadecimal code (#RRGGBB) or one of sixteen named color values. Named Colors: Black, silver, gray, white, maroon, red, purple, fuchsia, green, lime, olive, yellow, navy, blue, teal, aqua. Warning: These named color values are NOT consistent from browser to browser and platform to platform. If you want consistent color, you must use hexadecimal values. Web-safe color values: Netscape-safe, or Web-safe, color values involve combinations of the follow hexidecimal values: 00, 33, 66, 99, CC, FF. For instance, here are a few Web-safe color values: "#33CCFF", "#000000", "#FFCC66" Here are a few values that are NOT Web-safe: "#33AAFF", "#34AADF", "#FCDDFF" Again, hexadecimal code breaks the colors down into three positions: #RRGGBB. The first two digits represent the Red, the second two digits represent the Green values, and the third two digits represent the Blue values. Each of these two digits, in hex, represents a number from 0 to 255, which is the complete range of each color in the RGB color pallete. When using Photoshop, or any other image-editing software that uses a base10 color picker, remember the following chart: Base 10 vs. Base 16 0 00 51 33 102 66 153 99 204 CC 255 FF For instance, a color that is #3300CC in hex would be Red: 51 Green: 0 Blue: 204 in a standard color picker. Property: color Example: P { color: yellow } Cascading Style Sheet Properties Definitions Font and Font Style Properties Property: font-family Example: P { font-family: "Times", "Times New Roman", serif } "font-family" is the property to use when assigning specific, named fonts to an HTML tag. With this property, you can assign any font to display in a user's browser, even specialty fonts like "Univers", "Benguiat" or "Amigo"; this, of course, assumes that the user has such special fonts loaded onto their computer. You should include at least one font name that is absolutely standard, such as "Times", "Times New Roman", "Palatino", "Courier", etc. Font names should be separated by commas. As a last resort, you should make certain to include one of the generic font names given below; otherwise, the browser may revert to the default browser font. There are five generic font names: serif: displays font like "Times" or "Times New Roman" sans-serif: displays font like "Helvetica" or "Arial" monospace: displays font like "Courier" or "Courier New" cursive: displays font like "Zapf-Chancery" or "Script" fantasy: displays font like "Western" or "Comic" Note: font-family is the only CSS property which uses quotation marks to delimit its values. The font names should be spelled, in mixed case, exactly as they would display in a user's Font menu on their computer; if you don't spell these names using mixed case in this manner, font-family will not operate correctly. Warning: fantasy and cursive are not fully implemented. Property: font-size Example: P { font-size: 24pt } Outside of the regular units of measurement for font sizes, you may also indicate font size using these relative units: xx-small, x-small, small, medium, large, x-large, xx-large. (Medium is the standard size, about 10 to 12 points. Each size is 50% larger or smaller than the size adjacent.) smaller: 50% smaller than the parent element's font larger: 50% larger than the parent element's font Property: font-style Example: P { font-style: italic } If you want italic or oblique styles, use this property. Values: normal, oblique, italic Property: font-weight Example: P { font-weight: bold } If you want bold text, use this property. Values: normal, bold You may also state font-weight using values, in increments of 100, from 100-900. 100 is the thinnest possible font-weight, while 900 is the heaviest possible font-weight. These font weights will only operate correctly if the user has a variety of versions of one font face loaded into their computer, which encompass everything from Light, Book, Medium, Bold, Black, etc. Example: P { font-weight: 200 } Property: text-decoration Example: P { text-decoration: underline } If you want underlines, strike-throughs or (Netscape-only) blinks, use this property. Values: underline, line-through, (blink) Review: font-family: "font name", "second font name", genericFontName font-style: italic font-weight: bold text-decoration: underline text-decoration: line-through More Text Formatting Property: text-indent Use this property to indent the first line of text. You can also set this to a negative number if you want the first line of text to hang off the left edge of the paragraph (if you do this, be sure to set the "margin-left" property to a positive number, or your text might disappear off the edge of the browser window). Value: any valid unit of measurement Property: line-height This property deals with the "leading", or the amount of space allotted vertically to each line of text. Values: any unit of measurement (point sizes recommended), a percentage (which is relative to the parent tag's line-height property), or "normal" Property: text-align This property allows you to set the alignment of a block of text: right, left, center. justify, where the text lines up on both the right and left margins, is only enabled in Netscape Communicator 4 and IE 4; Internet Explorer 3.0 will display justified text with a left alignment only. Values: right, left, center, (justify) Margin, Border, and Padding Properties According to the W3C, there are four conceptual parts of each element on a given HTML page: 1) The element itself. 2) The padding around the element. With tables, you encountered padding with the CELLPADDING attribute, where space was placed around text or elements within the bounds of a table cell. Padding is essentially the space between the element and its border. 3) The border of the element. Borders can be visible or invisible, and can have width of their own. 4) The margin around the element. A margin is the space between the border of an element and the edge of the page, or the space between the border of an element and its neighbor (if a neighbor also has a certain amount of margin attached to it, then that additional margin will be added to the space separating the two elements). Unfortunately, margin, border and padding properties have not been implemented consistently or completely in Netscape and Microsoft products. Margin works completely, but the others do not (see Webreview.com for comments). Property: margin Value: any valid unit of measurement Description: sets the margin for an element evenly, all the way around (top, right, left, and bottom). To set individual portions of the margin separately, use the following specific properties: margin-left, margin-right, margin-top, margin-bottom Theoretically, padding and border will operate in the same fashion. Property: padding Value: any valid unit of measurement padding works, setting space around an element evenly. Individual adjustments to padding-left, padding-right, padding-top, padding-bottom, however, may not work across all browsers. Property: border Value: integer representing pixel width, and color hex code Example: P { border: 1px #CC3333 } Border does not work uniformly across browsers. Setting individual portions of the border using border-left, etc, does not work properly at all. Backgrounds Background colors and images may now be applied to any element on a page, not just the BODY area. That means that individual paragraphs or DIV tags can have their own colors. Property: background Value: hex code for color, URL for background image using the following syntax: BODY { background: url(./graphics/myBackground.gif) } Notice how there are NO quote marks used in calling the url information? Rather, we now use the url() call to hold the relative or absolute url information for the location of the background image. We may assign a background color using the following syntax: BODY { background: #FFFFFF } We may also assign a background color AND a background image, just by placing a space between the two values: BODY { background: #FFFFFF url(./graphics/myBackground.gif) } We could also assign this background formatting information to a paragraph: P { background: #FFFFFF url(./graphics/myBackground.gif) } There is a great deal more which can be said about the background property. There are additional background properties which control the repeat, or tile, of a background image, the positioning of a background image, and any number of other tweaks and tricks. Unfortunately, these have not all been implemented consistently from browser to browser; please review http://www.webreview.com for the latest information. The IMG tag DO NOT format the IMG tag in CSS; doing so will cause severe problems involving the flow of text around left- or right-aligned images. Continue to use the traditional BORDER, ALIGN, VSPACE and HSPACE attributes in each