CSS Graphic Cascading Style Sheets Web Page Presentation

Cascading Style Sheets (CSS) are used with HTML to separate the look and formatting of a web page from its content. CSS contain presentation rules which can flow down (cascade) a hierarchy of HTML elements know as the DOM. CSS also has the ability for some rules to be inherited. This blending together of rules provides a consistent presentation for all the web pages of a web site. CSS permits the rules to be centralized, improving web page performance and simplifying web page maintenance. Newer versions of CSS allow for adaptive web page presentation which can account for variations in devices, such as display screen dimensions.

CSS have been evolving since 1996. CSS version 3 (CSS3) is the most recent version. The World Wide Web Consortium (W3C) maintains the standards for the different versions of CSS. The major versions of CSS are:

CSS Versions
Name Date Specifications
CSS 1 1996 Fonts, Colors, Alignment, Spacing
CSS 2.1 2004 Layout Positioning
CSS 3.0 On Going Effects, Sizing, Speech

CSS Layer in Web Pages Web Pages Layers

Web pages are commonly divided into three layers:

  1. Content
    The content layer contains the information the author desires to convey. The web page content is coded using a markup language (e.g. HTML). Every web page has a content layer.
  2. Presentation
    The presentation layer determines the appearance of the web page. The web page appearance is defined by the style rules contained in CSS.
  3. Behavior
    The behavior layer determines how the web page responds to varying factors, such as user inputs and browser capabilities. The behavior capabilities are created through the use of scripts such as JavaScript on the client-side and PHP on the server-side.

There are advantages to keeping these layers contained in their own individual files, as opposed to mixing the layers into a single document. A good programming practice is separate the web page layers into individual files:
  1. Content -> HTML file (e.g. index.html)
  2. Presentation -> CSS file (e.g. styles.css)
  3. Behavior -> Script file (e.g. knote.js or knote.php)

CSS Syntax and Coding Sheet Basics and Layout

The first line of an external style sheet should be a declaration of the character encoding, usually utf-8:

@charset 'utf-8';

The declaration helps in localizing the web pages correctly and is required for certain aspects of some browsers to be rendered correctly. However, the character encoding in an HTTP header will take precedence over this declaration.


Selectors Pattern Matching

A selector is a pattern used to find elements in the DOM. These patterns range from simple to complex. The pattern matching complexity has increased with each version of CSS. CSS3 has several new selectors that are very powerful.

Selectors are a core component of CSS. In CSS a declaration defines the property values associated with particular elements. These property values affect how the elements are displayed. A CSS declaration consists of:

  1. Selectors - Defining which elements are involved in the declaration.
  2. Property Specifications - {property : value} pairs that assign a value to a property.
A simple example of a CSS declaration is:

h1 {
 font-family: serif
}

which instructs the browser to use a serif font when displaying all the h1 header elements.When the same property specifications apply to multiple element types, the selectors can be declared in a comma-separated list, such as:

h1, h2, h3, h4 {
 font-family: serif
}
Simple Selectors Universal, Type, Class, ID
  1. Universal Selector (*), selects all elements. This was used as the first CSS reset which would set the margin and padding of all page elements to 0.

    * { 
     margin: 0;
     padding: 0;
    }
  2. Type Selector (p), selects all elements with the specified tag type. Such as all <p> elements:

    p {
     text-indent: 1em; 
     text-align: justify; 
     margin: 1.5em 1.5em 1.5em 0
    }
  3. Class Selector (.mediumCenter), selects all elements with the specified class. Such as all elements which contain a class of "mediumCenter":

    .mediumCenter {
    width: 60%;
    margin-left: auto;
    margin-right: auto;
    text-align: center }
  4. ID Selector (#search), selects all elements with the specified ID. Such as all elements which contain an ID of "search":

    #search {
    float: right;
    clear: both;
    margin: 10px 0px 0px 0px }

Attribute Selectors Attribute: Exists, Contains, Starts, Ends
  1. Attribute Exists (img[alt]), selects all elements of a specified type that have the specified attribute. Such as all <img> elements which have an "alt" attribute:

    img[alt] {
     border-style: none;
    }
  2. Attribute Contains (img[alt='Phone Icon']), selects all elements of a specified type that have the specified attribute containing the specified value. Such as all <img> elements which have an "alt" attribute containing the value of 'Phone Icon':

    img[alt='Phone Icon'] {
     margin: 12px 0 0 0;
    }
  3. Attribute Starts With (a[href^='http']), selects all elements of a specified type that have the specified attribute which starts with the specified value. Such as all <a> elements which have an "href" attribute starting with the value of 'http'. These are external links.

    a[href^='http'] {
     color: #2A5DB0;
    }
  4. Attribute Ends With (a[href$='htm']), selects all elements of a specified type that have the specified attribute which ends with the specified value. Such as all <a> elements which have an "href" attribute ending with the value of 'htm'. These are internal links.

    a[href$='htm'] {
     color: #FF5DFF;
    }

Relationship Selectors
  1. Descendant Selector (nav a), selects all elements of a specified type that have the specified type of parent. Such all <a> elements which hav a <nav> element as a parent:

    nav a {
    float: left
    }
  2. Immediate Child Selector (ul >li), selects all elements of a specified type that are the immediate children of the specified parent. Such as all <li> elements which are an immediate child of a <ul> element:

    ul > li {
     background-color: #EEE 
    }
  3. Adjacent Sibling Selector (div + p), selects all elements of a specified type which have siblings and are the immediate child of a specified parent. Such as all <p> elements which have siblings and are immediately after a <div> element:

    div + p {
     background-color: #EEE
    }
  4. General Sibling Selector (h2 ~ p), selects all elements of a specified type that have the same specified parent. Such as all <p> elements which have the same <h2> parent element:

    h2 ~ p {
     background-color: #EEE
    }

Positional Selectors first-child, last-child, nth-child

Positional selectors select specified child elements of a specified parent type. The child specifiers include:

  1. :first-child - Select first child of element. (CSS 2)
  2. :last-child - Select last child of element. (CSS 2)
  3. :nth-child - Select specified child of element. (CSS 3)
Example1: Change the background color of every third row in a table:

table.thirds tr:nth-child(3n) { 
 background-color: #F00;
}
table.thirds tr:nth-child(3n-1) { 
 background-color: #0F0;
}
table.thirds tr:nth-child(3n-2) { 
 background-color: #00F;
}

Example 2 : Change background color of every other odd numbered row in a table:

table.ncshort tr:nth-child(2n-1) { 
 background-color: #EEE;
}


CSS Layouts Display, Position, Float, Templates, Frameworks
The position of elements on a page are controlled by properties. Different elements can be used as structures to organize the page contents. Many CSS templates and frameworks are available to aid with CSS layouts.


Display: block, inline, none
Display is an important property for controlling layout. Every element has a default display value which depends on the type of element. Most elements have either block or inline as their default display property.

Block - a block element takes up the full width available and has a line break before and after it. Examples of block elements are:

<div>
<p>
<form>
<footer>

Inline - an inline element takes up no more space that is required for its content. A common use of inline elements is to modify strings of text. Examples of inline elements are:

<span>
<strong>
<b>
<i>

None - None is a display value that will not display the element nor will it display the space on the page for the element. This differs from the visibility:hidden specification which will leave an empty space on the screen where the element would have been displayed.

Setting the width property on a block element will stop it from expanding horizontally. If the window is smaller than the width property a scroll bar appears. However if the max-width property is used instead of the width property, the content realigns itself in the smaller window and the scroll bar is not necessary to see all the content.


position: static, relative, fixed, absolute, float
Another important property for CSS layouts is the position property. The position property can have the following values:

1. Static - This is the default position value for all HTML elements. This causes the element to be positioned according to the normal flow of the page. Static positioned elements are not affected by the top, bottom, left, and right properties.

2. Relative - This also causes the element to be positioned according to the normal flow of the page. However relative positioned elements can use the top, right, bottom, and left properties to be adjusted away from its normal position.

3. Fixed - This causes the element to maintain the same position relative to the browser window. This means the element will always display on the same place on the page even when the page is scrolled.

4. Absolute - This behaves like fixed except it is positioned relative to the nearest positioned ancestor. If there is no positioned relative, it positions relative to the document body. Absolutely positioned page elements are removed from the documents normal flow and can overlap other elements.

Another CSS property is float. This causes the element to be pushed to the left or right, allowing other elements to wrap around it. Float is frequently used with images. The clear property is used with float to specify which sides of the floated element another floating element is allowed.

Layout Examples
Layout Example 1 - Divisions

Is a block element used to divide the page into logical sections. These divisions can be floated (float: left, right, inherit, none) or can be aligned horizontally (text-align: center, left, right) and vertically (nested divs tricks.)

<div style="background-color: red; text-align: left">
   This is division one.
</div> 
  
<div style="background-color: blue; text-align: center">
   This is division two.
</div>

<div style="background-color: green; text-align: right">
   This is division three.
</div>  

This is division one.
This is division two.
This is division three.
Layout Example 2 - Tabular
Used to define an outer division as a container with the layout of the inner divisions similar to cells in a table.

<div style="background-color: red; display: table">>
  This is division one.  
    
  <div style="background-color: blue; text-align: center; display: table-cell ">
    This is division two.
  </div>   

  <div style="background-color: green; text-align: right; display: table-cell ">
    This is division three.
  </div>   
</div>   

This is division one.
This is division two.
This is division three.
Layout Example 3 - Columns

Used to put list items into a specified number of columns.

<ul id="myul">
<li style="background-color: red;">
This is list item one.
</li>
<li style="background-color: red;">
This is list item two.
</li>
<li style="background-color: blue;">
This is list item three.
</li>
<li style="background-color: blue;">
This is list item four.
</li>
<li style="background-color: green;">
This is list item five.
</li>
<li style="background-color: green;">
This is list item six.
</li>
</ul>
  • This is list item one.
  • This is list item two.
  • This is list item three.
  • This is list item four.
  • This is list item five.
  • This is list item six.


CSS Templates and Frameworks
There are a number of templates available for CSS layouts. Some available templates are:

Primary CSS
Max Design
Iron Myers
Dynamic Drive
Matthew James Taylor

There are a number of CSS Frameworks that make CSS layouts easier. Some of those are:

960 Grid System
Blueprint CSS
BlueTrip
Bootstrap
Foundation
Kube
GroundworkCSS

Browser Compatibility Documentation, Testing, and Coding Techniques

While most browsers fully support the CSS 2.1 standard, the support for the developing CSS 3.0 standard still varies considerable among browsers. The Quirksmode and Can I Use web site contains a reference of CSS and browser compatibility. Wikipedia also provides details about the CSS compatibility of various web browsers (and their core layout engines ). The CSS3 Test will test which CSS3 features the accessing browser recognizes. Browser Shots can help determine how web pages will appear in various browser versions. A batch request can be submitted through Browser Shots to receive screen captures of web page displays in Windows (up to 122 browser versions), Linux (up to 69 browser versions), and on the Mac operating system (up to 9 browser versions).

One technique for handling the incompatibilities among browsers is graceful degradation. This involves coding web pages so if a browser does not support a more recent standard, then the web page falls back to an earlier standard the browser can support. A similar technique called progressive enhancement works in the opposite direction. It first supports the older browsers and then adds new capabilities supported by modern browsers. The final result in both techniques is specification of the lower versions of CSS rules before higher versions of CSS rules. For example, some older browsers do not handle the RGBa function that allows setting of color transparency with the alpha parameter. So you first specify the color with the old, more widely supported, RGB function. Then specify the color with the new RGBa function. The last command the browser recognizes will be used. So modern browsers will us the RGBa function, and older browsers will fall back to use the RGB function.

background: rgb(255, 255, 255);         /* Fallback */
background: rgba(255, 255, 255, 0.6);   /* 60% Opacity, if Browser Supports It*/

Cascading and Inheritance Mechanisms for Rule Propagation

Style rules can be passed down by two different mechanisms:

  1. Cascade
    Style rules can be passed down through the DOM from different sources. The origin and order of the rule definition are factors in determining the rules precedence.
  2. Inheritance
    A style rule can be obtained from it's parent element. However not all rules can be inherited. Typically text related rules (e.g. fonts, lists) are inherited, while box related rules (e.g. margins, padding, borders) are not inherited. See the Full Property Table for CSS version 2.1 for documentation on rule inheritance capabilities.

CSS Precedence - Developer Tools The Easy Way

Before delving into the theory of CSS precedence, it should be pointed out there is an easy way to determine which rule has precedence. All the major browsers have Developer Tools which allow you to see which rules are taking precedence. In Chrome I inspected a span element with a "subheading" class defined. In the Styles section you can see the span element inherited a font size of 100% from the body element. However a more specific rule for the "subheading" class takes precedence and reduces the font size to 80%.

Chrome Snip 1


CSS Precedence - Theory Check Caffeine Level Before Proceeding

The CSS rule which applies to an HTML element is determined by a combination of the rule's:

  1. Origin
  2. Source Order
  3. Importance
  4. Specificity
These factors determine a weight which is used to define, without ambiguity, which rule is applied to the HTML. The rule with the highest weight takes precedence. Further explanation of each of these list item:
1. Origin
Below are possible locations for CSS rules, in order of increasing weight.
  1. Default Style Sheet (aka User Agent Style Sheet, Contents Created and Varies by Vendor, External to HTML)
  2. User Style Sheet (Specified in Browser by User, External to HTML)
  3. Author Style Sheet (Created by Web Page Author, Linking/Importing, External to HTML)
  4. HTML Head Section (In Top Section of the HTML Document)
  5. HTML Inline (Contained in the Style Attribute of HTML Element Definition)
2. Source Order
When the same rule is specified from the same location, the last rule defined is assigned the highest weight. Consider this example with multiple author style sheets:

An HTML document links in style sheet styles1.css, followed by styles2.css and styles3.css. Styles3.css imports styles4.css. Style sheets 1,2, and 4 each contain a different rule for the same HTML element. The rule defined in style sheet 4 will take precedence because it was the last rule read in by the browser.
3. Importance
The CSS !important declaration dates all the way back to CSS version 1 as a way for style sheet creators to increase the weight of their rules. This declaration can provide an exception to the Origin and Source Order rules listed above. Two important examples are:
  1. A rule with an !import declaration in a user style sheet will take precedence over a rule in an author style sheet which does not have the !important declaration.
  2. A rule with an !import declaration in an author style sheet will take precedence over a rule in an user style sheet which also has the !important declaration.
4. Specificity
If two or more rules for a HTML element have the same origin and importance, then specificity is a calculation used to determine which rule has precedence. The rule calculated to have the most specific HTML selectors takes precedence. The W3C publishes the method for calculating a selector's specificity which I am paraphrasing as:
For each competing rule, concatenate the four calculated numbers a-b-c-d and the rule with the largest number takes precedence. The method of calculating the numbers is:
  • a = 1 if rule is from a style attribute of the HTML definition, otherwise it is 0.
  • b = count of the number of ID attributes in the selector
  • c = count of the number of attributes and pseudo-classes in the selector
  • d = count of the element names and pseudo-elements in the selector
An example calculation for competing List Item rules, in order of increasing specificity is:

		            li        0001
		            ul li     0002
		            li.accent 0011
		            li#health 0100

Top | Selectors | Layouts | Browser Compatibility | Precedence
References
  1. Marco Casario; Nathalie Wormser; Dan Saltzman; Anselm Bradford; Jonathan Reid; Francesco Improta; Aaron Congleton (2012). CSS3 Solutions: Essential Techniques for CSS3 Developers Springer Science+Business Media New York, ISBN-10: 1-4302-4335-X.
  2. Duckett, Jon (2011). HTML & CSS Design and Build Websites John Wiley and Sons, ISBN 978-1-118-00818-8.
  3. Lunn, Ian (2013). CSS3 Foundations John Wiley and Sons, ISBN 978-1-118-42516-9 .
  4. Mozilla Developer Network, Cascading Style Sheets. Retrieved January 24, 2013.
  5. SitePoint, CSS Reference. Retrieved January 24, 2013.
  6. {CssDog}, Home Page. Retrieved January 24, 2013.
  7. CSS Play, Experiments with Cascading Style Sheets. Retrieved January 24, 2013.
  8. W3C, CSS 2.1Selectors. Retrieved January 27, 2013.