37
CSS Methodology by Zohar Arad

CSS Methodology

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: CSS Methodology

CSS Methodology

by Zohar Arad

Page 2: CSS Methodology

What is CSS?

CSS stands for Cascading Style Sheets and is the language used for implementing designs on HTML documents.

CSS is a declarative language, not a programmable language.

Currently the main-stream version of CSS supported by all major browsers is CSS 2.1

Page 3: CSS Methodology

CSS Basics - Selectors

CSS declarations are comprised of "selectors" and "properties".

Selectors are used to select the element(s) in the page the declaration is applied to.

Properties are used to denote which styling properties should be applied to the selected element(s)

Example:

selector{    property:value;}

Page 4: CSS Methodology

CSS Basics - SelectorsSelector Pattern Description

Universal * Matches any element

Type (element) E Matches any E element

Class .class Matches any element with class="class"

ID #id Matches any element with id="id"

Descendant E D Matches any element D who is a descendant of element E

Child E > D Matches any element D who is a direct child of element E

Sibling E + D Matches any element D who is a direct sibling (adjacent) of element E

Attribute E[attr]E[attr=val]E[attr~=val1 val2]E[attr|=val]

Match element with attrattribute is equal to valattribute is equal to val1 or val2attribute is not equal to val

Pseudo-classes :hover, :active, :visited, :link,:first-child, :first-line, :first-letter :before, :after

Page 5: CSS Methodology

CSS Basics - Selectors

The following selectors are not supported in IE6:

• Child selectors - E > D• Sibling selectors - E + D• Attribute selectors - E[attr] ...• Multiple class selectors - E.myclass.active• Pseudo-classes - :before, :after, :first-child, :focus, :lang• :hover pseudo-class only works on <a> elements

 You can use this to target IE6 specific CSS: #myID #container { background-image:url(/transparent.gif); } /* IE6 */

#myID > #container { background-image:url(/transparent.png); }

Page 6: CSS Methodology

CSS Basics - Conflict Resolution

When two CSS selectors target the same element(s), how does the browser know which declaration (CSS block) should be applied?

This problem is known as CSS Conflict Resolution and is resolved on three levels:

1. Cascade - selector level– Importance - declaration level– Specificity - selector level

Page 7: CSS Methodology

CSS Basics - Conflict Resolutioninline styles ID selectors Class selectors Type selectors

1 1 1 1

p - 0,0,0,1 p.class - 0,0,1,1 #nav li.active - 0,1,1,1

.ie .menu a:hover - 0,0,3,1

form input[type=submit] - 0,0,0,2

Page 8: CSS Methodology

CSS Basics - Conflict Resolution

Using the specificity table above we can determine how the browser will choose between two selectors that target the same element(s).

Specific selectors will always take precedence over less specific selectors.

Specificity works at the selector level. If two selectors with different specificity contain different CSS properties, there will be no conflict between them.

Page 9: CSS Methodology

CSS Basics - Conflict Resolution

For example:  a:hover{ /* specificity 0,0,0,1 */    color:blue; /* affects link color */}

li a:hover{ /* specificity 0,0,0,2 */    text-decoration:underline; /* affects link decoration */}

#post a:hover{ /* specificity 0,1,0,1 */    color:red; /* affects link color - conflicts with a:hover */}

Page 10: CSS Methodology

CSS Basics - Conflict Resolution

When two or more CSS selectors have the same specificity and target the same element(s), how will the browser choose which will take precedence?

According to the cascade, selectors are evaluated in the order they appear in the document. Therefore, selectors that appear late in the document will take precedence over selectors that appear early in the document.

Page 11: CSS Methodology

CSS Basics - Conflict Resolution

When a browser evaluates CSS document it does so in the following order:

1. User-agent CSS - lowest precedence– Developer CSS - second-lowest precedence– User-defined CSS - highest precedence

 The rules of the cascade will be applied to the above CSS in ascending order.Like specificity, the cascade works at the selector level.Two overlapping selectors with different CSS properties will not cause a conflict.

Page 12: CSS Methodology

CSS Basics - Conflict Resolution

When two conflicting selectors contain the same CSS property / properties, how does the browser choose which property to apply?

CSS properties can be marked as "important" which will mean they should take precedence over identical properties in conflicting selectors.

For example:

body { color:black !important; }

div a { color:blue; }

Page 13: CSS Methodology

CSS Basics - Conflict Resolution

Putting everything together:

When two or more selectors target the same element(s) the browser will:

1. Try to resolve conflicting properties using specificity– Try to resolve conflicting selectors using the cascade– Try to resolve conflicting selectors using importance

 Specificity has the lowest precedence and importance has the highest precedence.When resolving conflicts using importance, the rules of the cascade still apply!

Page 14: CSS Methodology

CSS Basics - The Box Model

The box model defines how the browser should handle the rectangular boxes that are generated for elements. See image below or a 3D diagram 

Page 15: CSS Methodology

CSS Basics - The Box Model

In simple terms we can say that the box model defines the calculation of box dimensions as following:

total width = border-right + padding-right + width + padding-left + border-left

total height = border-top + padding-top + height + padding-bottom + border-bottom

 Why is this important you ask?

Simple - So we can calculate element dimensions when planning our layout.

Page 16: CSS Methodology

CSS Basics - The Box Model

A few things to remember:

Block-level elements have explicit dimensionsInline-level elements have implicit dimensions

Floating an element will cause an element to lose its width, unless set explicitly (as required by CSS specifications)

Vertical margins are collapsed by the browser only so the larger of the two will take effect.

Page 17: CSS Methodology

CSS Basics

Feedback and 5min break

Page 18: CSS Methodology

CSS Best Practices & Tips

Reset styles to eliminate browser inconsistencies (example) Use meaningful markupSeparate content from display

Use meaningful class and ID names

Use specific selectors for faster parsing

Harness the power of the cascade and CSS inheritance to your advantage  

Page 19: CSS Methodology

CSS Best Practices & Tips

Plan your layout carefully during the HTML coding stage

Group similar-styled page components together

Define typography once at the beginning of your CSS document

Use browser-specific CSS handicap to your advantage when trying to handle browser-specific problems

#nav li a { ...some css for ie6 }#nav li > a { ...some css for all browsers }

Page 20: CSS Methodology

CSS Best Practices & Tips

Use IE conditional comments to apply global IE selectors: <!--[if lt IE 7 ]><body class="ie" id="ie6"><![endif]--><!--[if IE 7 ]><body class="ie" id="ie7"><![endif]--><!--[if IE 8 ]><body class="ie" id="ie8"><![endif]--><!--[if !IE]><!--><body><!--<![endif]-->

Page 21: CSS Methodology

Design Deconstruction

When approaching a new project, it might be useful to deconstruct the design as follows:

• Look at content without design - Analyze what's the site's content structure so you can plan your HTML accordingly

• Analyze the proposed layout and identify common patterns and pitfalls

• Analyze the design's typographic structure and implement at the beginning of your CSS

• Identify graphic patterns that should be grouped into a CSS sprite. Use as few sprites as possible. If needed separate pattern sprites from icon sprites.

Page 22: CSS Methodology

Design Deconstruction

• Try to identify browser-specific pitfalls in the design and either account for them in your plan or remove from design

• Try to identify what kind of interaction effects you should implement in the design and opt for CSS-driven effects whenever possible.

• Implement your UI once! If there are UI inconsistencies, either ignore or educate your designer.

• Identify resource-hungry decorations and put them on low-graphics diet.

• Reuse! Reuse! Reuse! Lets look at Ars Technica, Smashing Mag. and Linux.com

Page 23: CSS Methodology

Break...

 

Page 24: CSS Methodology

Javascript

Javascript is a fickle friend!!!

Its a bit old, its a bit off-standard, it sort-of has an OOP model, but when you get to know it, its oodles of fun!

Page 25: CSS Methodology

Javascript - The basics

Javascript runs on the client which means that execution speed depends on the rendering engine and the user's computer

In other words - The same Javascript code will run differently on two computers.

Page 26: CSS Methodology

Javascript - The basics

If you can't beat them, join them!• Minimize DOM complexity• Include your Javascript where appropriate in the DOM• Load Javascript on-demand if possible• Cache your Javascript whenever possible• Reduce file size to reduce initial parsing time• Reduce network traffic to minimum• Simplify your code to optimize execution time• Validate your code with JSLint or similar

Page 27: CSS Methodology

Javascript - The basics

Understand Javascript variable-scope.

• Javascript variables has no private/public name-spaces• Variables can be either global or local - beware of collision• Declare variables explicitly to denote type and initial value

and avoid name collisions• Optionally, use Javascript Objects as variable containers

 var params = {    name : 'zohar',    age : 34,    height: 187,    skills : ['css', 'js', 'xhtml'] }

Page 28: CSS Methodology

Javascript - The basics

Know thy DOM

DOM is the mechanism we use to reference and manipulate our document's HTML. The DOM is a programmatic, object-oriented way to represent and handle HTML (XML) structure. In relation to text manipulation, DOM and XML parsing are very slow. Each rendering engine implements the DOM a bit differently.

Page 29: CSS Methodology

Javascript - The basics

Know thy DOM

• DOM calls are expensive. Use the when appropriate• Be specific in your DOM calls. Use getElementById when

possible• Cache DOM calls• Although considered "less" elegant, innerHTML is much

faster than document.appendChild()

Page 30: CSS Methodology

Javascript - The basics

Understand the meaning of "this"

"this" refers to the scope of code execution at any given point in the code, during execution time (not parse time).

The easiest way to remember what is "this" is as follows:

"this" will always refer to the object before the "." sign in the calling code.

Page 31: CSS Methodology

Javascript - The basics

function test(){    var _this = this; //this points to the window object}

myObj = {    run : function(){        console.log(this.name); // this points to myObj    } ,    name: 'zohar'}

myObj.run();

myElement.onclick = function(){    this.className = 'active'; // this points to myElement}

Page 32: CSS Methodology

Javascript - Programming Tips

Javascript short-hand is cool. Use it!

//one-line variable assignmentvar i = 0, arr = [], el = document.getElementById('id'); // default value assignment//arg1 is passed to the function var status = arg1 || 'active'; //variable assignment in if statementvar el;if( el = document.getElementById('id') ){ ..... }

Page 33: CSS Methodology

Javascript - Programming Tips

// selective method execution

myObj = {    func1: function() {},    func1: function() {} }

function test(status){    myObj[status == 'active' ? 'func1' : 'func2'](); }

Page 34: CSS Methodology

Javascript - Programming Tips

Use JSON for both parameters and code clusters to make your code more ordered and readable.

var tabManager = {    init : function(){ ... }    onTabChange : function() { ... }    params : {        active : 'active',        inactive : 'inactive'        tabsParentID : 'tabs'    }}

Page 35: CSS Methodology

Javascript - Programming Tips

Try thinking OOP in Javascript: var Class = function(obj){    return function(){        if(typeof obj.initialize === 'function'){            obj.initialize.apply(obj,arguments);        }        return obj;    }}

Function.prototype.bind = function(tgt){    var self = this;    return function(){        self.apply(tgt, arguments);    }();}

Page 36: CSS Methodology

Javascript - Programming Tips

Try thinking OOP in Javascript: var Test = new Class({    initialize:function(){        console.log('starting',arguments,this);        this.run.bind(this);        bindTest.bind(this);    },    run:function(){        console.log(this,'running');    }});

function bindTest(){    console.log(this,'bindTest');}

var t = new Test(true,10);

Page 37: CSS Methodology

Javascript

Questions Time