Cascading Style Sheets/Inheritance Rules

Summary

'The term CSS cascade'' refers to the decision process, the software within web browsers that decides which of the many cascading style sheet (CSS) styles to apply to each part of a web page. It is complex because there are many places that styles are written. There are errors, conflicts, and duplicates to contend with, not to mention the hierarchy of browser, user, and author rights that always exists. Nonetheless, the browser's software has to decide which style to use for every format on the page, and has to build a reasonable page even when no useful styles have been provided.'''

This page provides both an overview and a detailed example of a basic cascading process, and although it is capable of imparting detailed knowledge in the process, is not specifically intended to teach the making of web-pages or their style-sheets.

Web File Basics
Before describing the workings of the cascade, essentially just a part of the browser's functions, it might be as well to recall the basic features of the browser's surroundings.


 * A web page is the result of opening a certain text file with an .htm suffix.  The file can be written in a simple text editor. It resides on a distant computer that works as a server, but can also reside in some folder of the local personal computer (PC).   When its address is supplied to the browser, the file is downloaded to the browser cache, a temporary storage place on the PC.   The .htm file is sometimes referred to as the web-document.
 * The web-document has markings in it to help with its formatting, and it is the job of the web browser to apply the styles.  The web-document has pairs of markers called tags that surround the text that is intended for formatting.   The tags indirectly identify the formats by saying what kind of page structure it is to be; for example, lists  () , main headings   , sub headings   , ordinary paragraphs   , or perhaps table cells    .   All of these different elements of the page can have different formats.
 * The tags are a part of the language HTML, Hypertext Markup Language, although other languages can be used.  The tag names in the web page, for example the p in    , are listed in style-sheets, alone or with other terms, and it is these style-sheet selectors that list the descriptions of the intended formats. That is to say, the browser can find the correct style-sheet selector to format an element because their names are predictably similar.   The document element is said to be the intended target for that selector's styles.  The file type that lists these formats is called a Cascading Style Sheet (CSS).
 * A style-sheet is just a text file with a .css suffix, and can be written in a simple text editor .  The author style-sheet is most often  found within the same folder as the web-document itself, wheresoever that may be. In any case, the name and address of the style-sheet is provided by an entry in the web-document, so it is downloaded to the browser cache soon after the document itself.   In fact, there could be several style-sheets listed there, and each would be imported and processed for its styles before taking the next, and so on.
 * The PC user can change styles too. but his user style-sheet resides on the local computer.  The browser merges this sheet with all of the other styles, so that both sets of styles could affect some part of the page.   Of course, the user styles affect only the local display and are not seen by others.
 * There are other places where styles are to be found. They are sometimes written into the head section of the web-document, and as in-line styles within the tags on the page.  The browser also has its own style-sheet, the user-client sheet, to provide the basic layout when other style-sheets are missing.   Sometimes the default settings of the browser and built-in style-sheets can also impose on the outcome. All of these sources&#39; styles are merged by the browser.
 * The author styles are formed from three sources .  These are; the styles written directly into the web-document's head section, the linked style-sheets referenced within the head section, and the in-line styles within the main content of the page.   Sometimes listings in such linked style-sheets can themselves import more style-sheets.
 * Some styles can have more importance than others.  Styles written in any of the style locations, including those on the document itself, can have special !important markings to distinguish them from normal styles.   These markings allow an author or user to override normal styles.   This feature is of particular use in testing or to assert built-in browser styles over those of others.   There are also different ranks within both the !important and normal styles, set by where they were found, their so-called sources (more later).
 * Some styles have more specificity than others. The extent to which a style-sheet selector lacks generality, or has a narrow definition, is referred to as specificity.   For example, some paragraphs in the document might simply be a part of the document body, and their paragraph styles applied for the general case.   Some others might need special formats because they are paragraphs located within say, a table cell.   The browser can detect this more specific tag layout and give priority to the selector that best matches it.     Specificity is important in the cascade's decision-making, and its rules have been developed to a considerable extent (more later).
 * Style-sheet formats have some common features. . Figure 1 shows a typical style-block layout that might exist in a style-sheet.  In it, a selector is the main label for a set of style declarations, each of which is comprised of a property and a  value.   In the example, a style-sheet's selector called div ul  has two style declarations; one property for line-height has a value of 1.8em; another property for background has a value of darkgreen.   The number of possible selectors is not limited to single tag names, since, as in the example, these can be compounded to denote the nesting of one set of tags within another.   In the example, this selector applies its styles to every unordered list that is nested within a set of division (div) tags, but not to other examples of unordered lists that it finds.   The introduction of classes and id's can add even greater specificity to selector use.
 * Web standards and specifications are managed by the World Wide Web Consortium (W3C), and others.  For CSS styles, new standards are published periodically as recommendations.   These standards are tested in the beta-versions of browsers, and the discovered descrepancies and deficiencies collated.    Eventually a new recommendation is published.   Various of the W3C tutorials and specifications can be found in the See Also links below.

The Cascade in Overview
This section provides an intuitive rather than a detailed description of the cascade process. For those who already understand such things, it might be best to go directly to the section A Detailed Cascade Example where the work may be more to their liking. In any event, for those who need to learn or remind themselves about selectors and specificity, tutorials have been provided in the section CSS Tutorials. For those who intend to know more on the subject of HTML, there is an extensive external reference available at W3 Schools HTML, and for CSS there is [http://www.w3schools.com/css/default.asp. W3 Schools CSS].

To continue, the browser travels the web page tag by tag with a view to determining their styles. To do so it first identifies the nest, or part of the document tree within which the tag lies. This helps the browser to check the validity of the selectors that it finds. It then searches through all of the style sources, style-sheets and the document itself, looking for selectors that could affect the tag in question, again, bearing in mind the tag layout. If a selector applies, its style properties are listed in the order that they are found, and the result is a long list of properties that apply to that particular tag. There may be many of these declared styles in the list, or none, depending on the work done by the various writers, and it is clear that most of the properties that could have be declared for that tag will still be absent.

Style declarations can have a special marking to give them added priority over normal declarations and they use the !Important keyword to identify them. They are called Important declarations. In sorting its lists the browser segregates the !important declarations from any normal declarations. The browser then recognizes the five Importance Ranks, or Importance Layers, of Figure 2, where rank 1 has the lowest importance and rank 5 has the highest. Each property entry on the list is marked with one of the five importance ranks depending upon the selector's source and whether or not it is a normal or important declaration. The items are also marked with their specificities, weighted values that reflect how narrow a scope is intended for their application. A note is made of each source location, a marking that identifies where it was found and its location within the style-sheet.

The set of data is then sorted to group all of the similar properties, then within any similar sets found, (for example, ten different font-sizes proposed), they are sorted further for highest importance. With any closely contested sets after these sorts, they are again sorted for highest specificity, to eventually isolate a value for each distinct property in the list. The last deciding sort in the event that any two declarations are still matched, is the source position in which they were found; that is to say, the one that was considered last for the listing will prevail. The graphic of Figure 3 depicts the cascade of styles involved in the resolution of formats for a single paragraph tag, its details being identical to those of the detailed example in a later section.

Having decided which formats apply to the particular tag, the browser repeats the process for each and every tag on the page, after which it applies all of the formats with its rendering engine.

An important point to emphasize is that in making its property lists, the browser always makes lists in the exact order that they were encountered in its travels from the top to the bottom of the web page, and from the top to the bottom of each style-sheet that it encounters while it is doing so. It also honors the styles sequence found in the heading of the web page when adding to its lists. This method has consequences for the browser's resolution of conflicts where source-order is the deciding factor. Recall again that all of this listing activity takes place for each tag-pair on the page.

After Cascading
When the cascade has run its course, the original set of declared styles will have been reduced to a set of cascaded styles, but many properties will not have been declared in the first place. In order for the browser to function correctly there must be a single value for every property that is considered essential for that element's formatting. The browser fills these large gaps with its default actions. For each essential property that is missing, it first tries to inherit a suitable value from a parent element, that is, from the tags that surround it; if that is not possible for some reason, the browser assigns an initial value. Property Initial values are preset in Property Definition Lists, at design time. The result of applying these defaults is to make a comprehensive set of specified values, that includes every property that is needed, for each tag under consideration.

The next stage is to make computed values from the specified values, by considering say, any relative sizes that have been quoted. For example a font-size of 1em needs to be converted to a value in pixels by relating it to some point of reference. With some further adjustments of the set, used values result, and these are tried in the rendering of the page. These might be further adjusted to accommodate constraints in layout or to round font sizes, at which point they are referred to as the actual values.

The Cascade in Detail
In order to understand the cascade process in more appropriate detail, an example section has been prepared below. In it, it is possible to study the source style-sheets themselves and the document used for the example. It has been assumed that the browser is attempting to resolve the styles for the document's first paragraph tag. The style-sheet declarations that apply to that tag have been highlighted in green to help the reader to follow the process.

All of the selected properties for that nest, their importance ranks, specificities, and positions found within the sources themselves have been entered into a sortable table on this page. It remains only for the reader to follow the various listings and to sort the table using the buttons on it, to see the process that resolves these selections.

Cascade Sorting Table
Table 1 below has listed in it all of the properties that apply to the first paragraph tag in the example document, and they have been listed in the top to bottom order that they were found.
 * Firstly, the user style sheet user.css was listed from top to bottom. (1:1 to 1:6; six properties as the first source to consider).
 * Then the head styles, because they are located in the document above the style-sheet links.(2:1 to 2:4)
 * The author style-sheet was next, main.css; (these are marked as 2:5 to 2:13).
 * then the two in-line styles were added as items (2:14 to 2:15).
 * The browser's Client Style-sheet contributes too, so these have been added last of all (3:1 and 3:2).

These twenty-three items can be seen listed in Table 1.

To resolve which of these many competing styles are to result in use for the first paragraph, a sorting model that mimics the cascade's behavior can be used. Its effect is to sort the items:
 * first for property name
 * then for importance
 * then for specificity, in four steps
 * then, unnecessarily, for source order

Table 1 opens with the page in natural source order, and can be sorted by the reader to see how each step affects the cascade.

Upon successfully completing the sort, the items will be selected as if they comprised the set:

'To sort the set of listed styles to the qualifying few, first sort the Property column without the shift key, by pressing the arrow in its column heading, then after that, sort the remaining sortable columns from left to right, in the same way but while pressing'' the shift key. This brings the selections to the bottom or top of their distinct property sets, depending upon whether the user sorts ascending or descending respectively. To assist in first time use the items that will be selected are marked in blue'''. attribute ID selector Class selector Element selector Source order

font-size 30px p      (rank 5) user important 0      0       0       1       1:1       font-family Tahoma .Tahoma (rank 5) user important 0      0       1       0       1:2       font-family Times #para1 (rank 2) user normal 0      1       0       0       1:3       color blue #para1 (rank 2) user normal 0      1       0       0       1:4       font-style italic #para1 (rank 2) user normal 0      1       0       0       1:5       font-weight normal #para1 (rank 2) user normal 0      1       0       0       1:6       font-size 2em p      (rank 3) author normal 0      0       0       1       2:1       font-family Courier p      (rank 3) author normal 0      0       0       1       2:2       background green .toppara (rank 3) author normal 0      0       1       0       2:3       border 1px solid lightgrey .toppara (rank 3) author normal 0      0       1       0       2:4       font-family Calibri #para1.Tahoma (rank 4) author important 0      1       1       0       2:5       color black #para1.Tahoma (rank 4) author important 0      1       1       0       2:6       font-style normal #para1.Tahoma (rank 4) author important 0      1       1       0       2:7       font-family Garamond p      (rank 3) author normal 0      0       0       1       2:8       font-size 20px p      (rank 3) author normal 0      0       0       1       2:9       font-weight bold p      (rank 3) author normal 0      0       0       1       2:10       background white p      (rank 3) author normal 0      0       0       1       2:11       padding 10px p      (rank 3) author normal 0      0       0       1       2:12       background beige .mostparas (rank 3) author normal 0      0       1       0       2:13       font-family arial p inline (rank 3) author normal 1      0       0       0       2:14       padding 1.5em p inline (rank 3) author normal 1      0       0       0       2:15       Display Block p      (rank 1) browser client 0      0       0       1       3:1       Margin 1em 0 p      (rank 1) browser client 0      0       0       1       3:2

Some Conclusions

 * Notice in the correctly sorted table that most examples are selected on the basis of their rank order, or in other words, their importance.
 * The background properties however, are not resolved by importance or specificity, since these are the same for each of the background properties in the set.  They are selected only by source-order, that is to say, the order in which they were listed.
 * The two listings for the padding property on the other hand, have equal importance but differ in specificity.  The one from an in-line style is chosen on this basis..
 * Notice that in the above hierarchy the user's styles with the !Important keyword marking are given the highest priority of all, and that they can only fail by omission. That is to say, other styles can be used but only when a format was not specified there. In general the styles selected to represent an origin-level in the cascade can only impose on the eventual outcome if no source that is ranked above it in importance has set a value of its own.  This is displayed by the graphic of Figure 3 in a more intuitively way than the sorting table, but it shows the same example.
 * Perhaps a less obvious point in regard to this selection process is that declarations with the !important marking do not need a high specificity to prevail. That is to say, although the !important declarations are sorted within their own source rankings for specificity, it is quite conceivable that one with a low specificity will be selected to represent its rank.  Then because of the priorities of the ranked sources, the low-specificity item can prevail over one with much more specificity but less priority.  This gives very wide scope to !important declarations, and because they do, it is essential to narrow their specificity as much as possible in use.   For example, a normal declaration of high specificity in an author style-sheet: can nonetheless be overruled by a low specificity declaration: As well as affecting the specific example, this latter declaration would assert itself over all paragraph declarations with a normal priority.
 * Generalizing from perhaps too little data, it might be possible to say that the more importance that is given to declarations by their rank positions, the more attention needs to be given to narrowing their specificity if they are not to become too  overbearing in their scope.

CSS Tutorials
A selection of brief tutorials is given below. The intention is to provide short pieces that instruct in the basics of the subject matter, rather than indulging in lengthy discourse. There is a listing on the use of style-sheet selectors, and an explanation of specificity and some other things.

For those who intend to study CSS by changing the content of style-sheets and web-documents, it may be as well to issue a standard reminder about the caching of files.
 * When a browser preference (option) is changed a browser re-start is most often needed before it can take effect.
 * When a web-page or a style sheet is changed, the expected changes are unlikely to be seen unless the browser cache is first cleared and the page re-loaded.  Much confusion can result if this point is overlooked.   The cache-clearing methods for each browser are different, but there is usually a feature within the browser's preferences (options).   Sometimes drop-menu items provide for faster cache clearing, but at  other times it may be necessary to set the options to clear the cache on closure, then restart the browser to display the change.   For the Opera browser, the most convenient way to empty the browser cache is by the use of the drop-menu item Tools / Delete Private Data...

Style Declaration Specificity
Specificity is to the extent to which declarations lack generality; the extent to which they apply to a tag on the page as opposed to their applying to tags in general. The method of deciding such a matter has been developed to a considerable extent.

The method that is used calculates a weighted sum that represents the specificity. The way to calculate specificity is as follows:

For any given style-sheet entry, examine its selector, for example,. The selector is sometimes simple, having only one element, or like this, complex, with more than one. Construct a value for its specificity by adding to a total as follows:
 * For a universal selector (*) or an inherited value, add zero to the specificity total. 
 * For an in-line style, add 1000 to the total.  These are found only on the document.
 * For every ID selector mentioned, add 100 to the total.
 * For every class, pseudo-class, or attribute, add 10 to the total.
 * For every simple tag element and pseudo-element, add 1 to the total.

The highest value of specificity among competing style declarations within any one level results in its representing that level in the overall cascade. (See the graphic within the main page).