Upload
darren-gideon
View
54
Download
0
Embed Size (px)
Citation preview
CSS Concepts & Fundamentals
What developers need to know
CSS Advantages
1. Separation of content form presentation
2. Site wide consistency(ease of maintenance)
3. Bandwidth(re-useable styles, browser caching of external stylesheet)
4. Page reformatting(ability to tailor content for different target devices)
5. Accessibility
CSS Limitations
1. Poor controls for flexible layouts
2. Selectors are unable to ascend
3. Vertical control limitations
4. Absence of expressions (such as margin-left: 10% - 20px)
5. Lack of column declaration
6. Cannot explicitly declare new scope independently of position
7. Pseudo-class dynamic behavior not controllable(no way to limit or disable)
Not Covered in Depth
1. Review of all CSS properties and their values
2. CSS best practices (they are situational)
3. Image spriting and optimization
4. Optimization for server performance
• What is CSS?
• What are its advantages & limitations?
• How does it work?
• Important Concepts for Layout
• Basic Performance Recommendations
Concepts & FundamentalsWhat developers need to know
1. It is a style sheet language not a programming language
2. It separates the presentation layer from the document structure
3. It is used to define the presentation layer (look & feel) of a document or application
4. It must be used in conjunction with a markup language (HTML, XHTML, XML, SVG, XUL, etc.) or a software platform that supports it (e.g. JavaFX)
What is CSS?
A stylesheet language renders the presentation of structured document. It allows the content of a document to be reused in many contexts and presented in various ways.
A stylesheet is a set of stylistic rules that describes content (e.g. fonts, colors, position, etc.)
It does not have the ability to do evaluations, set variables, have functions, methods, or any type of programming logic within the stylesheets or within its stylistic set of rules.
What is a Stylesheet Language?
In the context of HTML the presentation layer is simply how the content is presented to the user (in most situations it referrers to the layout and the visual look and feel)
Before CSS many markup languages included a limited set presentational tags (e.g <b>, <i>, <u>, <font>, <blink>, etc.) for controlling the presentational layer. Some of which had additional presentational attributes (that ability to set text alignment, set a background image, etc.).
However, this force a programmer to create unique instances of tags on his page for any instance which made maintenance awkward and time consuming.
What is the presentation layer?
Say you want to show Luke Skywalker as a Storm Trooper. In this example his Storm Trooper armor is actually a part of him and can’t be swapped out for a different set of garb.
What does separation of the presentation layer mean?
So if you wanted to show Luke now in his Rebel Pilot gear you would have actually make a completely new version of Luke. Resulting in you having two Lukes.
Now if you want to show Luke as a Jedi Knight you would have to make another new version of him. Resulting in you have three separate distinct Luke Skywalkers instead of just one Luke with three sets of garb that he can change into.
With CSS each document’s presentational elements no longer has to be 100% unique.
Presentational elements can be defined once and then referenced by multiple objects instead of having to be define every time for each object
This allows for you to take the same document’s content and presented it differently depending on the media its viewed with
It also allows for the content to be displayed differently due to conditions a programmer defines and changes dynamically.
With CSS we can take a typical HTML element and easily present it differently to the user without having to “clone” it to achieve a different look .
<div id=“johnDoe” class=“himself”></div>
<img src=“johnDoeHimself.jpg” />
VS
<div id=“johnDoe” class=“himself stormTrooper”></div>
<img src=“johnDoeStormTrooper.jpg” />
VS
<div id=“johnDoe” class=“himself darthVader”></div>
<img src=“johnDoeDarthVader.jpg” />
VS
Nobody wants a clone army of John Does
<div id=“johnDoe”></div>
<img src=“johnDoe Himself.jpg” /><img src=“johnDoeStormTrooper.jpg” />< img src=“johnDoeDarthVader.jpg” />
VS
Well except for Emperor Palpatine and then with just one CSS class he can put all of his John Doe clones in Storm Trooper armor.
<div id=“johnDoeClone1” class=“stormTrooper”></div><div id=“johnDoeClone2” class=“stormTrooper”></div><div id=“johnDoeClone3” class=“stormTrooper”></div><div id=“johnDoeClone4” class=“stormTrooper”></div><div id=“johnDoeClone5” class=“stormTrooper”></div>
How does it work?
CSS is set of stylistic rules defined in either a external stylesheet, an embedded stylesheet, or inline styles coded directly in a tag element.
These rules use selectors to identify a structural element(s) and apply rules to it.
Accessing RulesCSS rules are accessed either by a document by having an:
1. External stylesheet
<link href=“css/starWars.css" rel="stylesheet" type="text/css" />
2. Embedded stylesheet
<style type=“text/css”> p { font-family: arial,helvetica,verdana; }</style>
3. Inline styles on individual elements (HTML tags)
<div style=“font-weight: bold;”>Jaba the Hut</div>
Basic SelectorsCSS is set of stylistic rules that uses a selector to identify a structural element and apply these rules to it.
The basic selectors to target HTML elements are:
1. HTML tag selector (applies to each instance of the tag)
e.g. html, body, p, ul, li, div, span etc.
2. Class selector (can be applied to multiple HTML tags and different type of tags)
e.g. <div class=“ewok”>text</div> <li class=“ewok”>text</li>
3. ID selector (IDs are unique can only occur once on a page)
e.g. <div id=“theEmpire”>text</div>
Descendent Selector
You can also specify a style via descendent selectors
div .ewok {color: #ff0000;
}
<div> <p id=“theEmpire”> <span class=“ewok”>text</span> <span class=“jarJarBinks”>delete</span> </p></div>
Child Selector
#theEmpire > span { color: #ff0000;}
<div><div id=“theEmpire”> <span class=“ewok”>text</span> <span class=“jarJarBinks”>delete</span></div>
</div>
You can specify elements that are direct descendents of another element.
Adjacent Sibling Selector
b + i { color: #ff0000;}
<div> <b>bold one</b> <i>italic</i> <b>bold two</b> <u>underline</u></div>
You can specify elements that immediately follow and share the same pattern as another selector (not support by IE6)
Universal Selector
# tatooine { color: #ff0000;}
<div id=“tatooine”><b>bold</b><i>italic</i><span>test</span><div>underline</div><p>
paragraph paragraph paragraph paragraph paragraph paragraph
paragraph paragraph paragraph paragraph paragraph paragraph </p>
</div>
Let you use a wildcard selector in place of an HTML selector (not support by IE6)
Pseudo-Classes
:active - element being clicked:first-child - element that is the first child or another element:focus - element that has screen focus:hover - element with mouse cursor over it:lang() - element with language code defined:link - element that has not been visited:visited - element that been visited
Examples
a:link { color: #ff0000; } a:visited { color: #660000; } a:hover { color: #cc0000; } #navBar:first-child { border-right: solid 1px #ffffff; }
p:lang(fr) <p lang=“fr”>Oui</p>
Many HTML elements have special states or uses associated with them that can be styled
Pseudo-Elements
:first-letter - first letter in an element (only block level element & limited properties,
inconsistent placement, IE8):first-line - first line in an element (only block level element & limited
properties, inconsistent placement, IE8)
:after - space immediately before an element (IE8+):before - space immediately after an element (IE8+)
Examples
.p:first-letter { font-size: 20px; } .p:first-line { font-weight: bold; } .indentPara:before { padding-left: 5px; content: “url(“bullet.gif) “; } .quoteText:after { font-style: italic; content: “{url(logo.gif”); }
It is a specific, unique part of an element.
Cascade
Cascade is what ultimately determines which properties will modify a given element. The cascade is tied to three main concepts:
importancespecificity source order
It follows these three steps to determine which properties to assign to an element. By assigning a weight to each rule and this rules determines which rule applies when more than one applies.
Importance
Styles can come from a different sources. This is a list of the ascending order of importance (the more important takes precedent over the less important)
User agent declarations (browser’s default styles)
User declarations (user’s browser options)
Author declarations (CSS provided by the page – inline styles, embedded stylesheet, external stylesheet)
Author !important declarations
Specificity
Every CSS rule has a particular weight. Upon assessing a rule’s importance the cascade attributes a specificity to it and if one rule is more specific than another it overrides it.
Element = 1 (a)Pseudo element = 1 ( a:first-letter)Pseudo class = 10 ( a:hover)Class = 10 ( <div class=“starWars”> )Attribute = 10 ( <styles type=“text/css”>)ID = 100 ( <div id=“dathMaul”>)Inline style = 1000 ( <div style=“font-family: arial;”>!important = Overrides all (color: #ff0000 !important)
Visual way to think of SpecificitySome people prefer a visual way to evaluate specificity weight instead of doing math. Andy Clarke did an analogy between Star Wars and CSS specificity in 2005 which I have expanded on a little. So if CSS was specificity was Star War characters:
Visual way to think of SpecificitySome people prefer a visual way to evaluate specificity weight instead of doing math. Andy Clarke did an analogy between Star Wars and CSS specificity in 2005 which I have expanded on a little. So if CSS was specificity was Star War characters:
Visual way to think of SpecificitySome people prefer a visual way to evaluate specificity weight instead of doing math. Andy Clarke did an analogy between Star Wars and CSS specificity in 2005 which I have expanded on a little. So if CSS was specificity was Star War characters:
Visual way to think of SpecificitySome people prefer a visual way to evaluate specificity weight instead of doing math. Andy Clarke did an analogy between Star Wars and CSS specificity in 2005 which I have expanded on a little. So if CSS was specificity was Star War characters:
Visual way to think of SpecificitySome people prefer a visual way to evaluate specificity weight instead of doing math. Andy Clarke did an analogy between Star Wars and CSS specificity in 2005 which I have expanded on a little. So if CSS was specificity was Star War characters:
!importanceIt winsbecause it blows up planets
Let’s calculate some specificity
Let’s calculate some specificity
Let’s calculate some specificity
Let’s calculate some specificity
Let’s calculate some specificity
Let’s calculate some specificity
Source Order
Source order applies in the case of when two rules share the same weight, source, and specificity. In this case the last one is applied.
In one style sheet you could have:
line 341: .pullQuote { font-size: 14px; } line 781: .pullQuote { font-size: 12px; }
Source Order
Source order applies in the case of when two rules share the same weight, source, and specificity. In this case the last one is applied.
In one style sheet you could have:
line 341: .pullQuote { font-size: 14px; } line 781: .pullQuote { font-size: 12px; }
The page would use the font-size from line 781
Source Order
Source order even applies when two different external stylesheets are used.
Both style sheets define an unordered list:
line 12: styles.css ul {margin: 0px 0px 0px 0px } line 13: corporate.css ul {margin: 10px 0px 10px 10px }
Source Order
Source order even applies when two different external stylesheets are used.
Both style sheets define an unordered list:
line 12: styles.css ul {margin: 0px 0px 0px 0px } line 13: corporate.css ul {margin: 10px 0px 10px 10px }
Since corporate.css comes after styles.css the page uses its rules for the ul tag.
Source OrderSo what happens with two death stars (!important declarations) fight?
<style type="text/css"> p { color: red !important } p { color: blue !important }</style>
Source OrderThe last death star (!important declarations) wins!
<style type="text/css"> p { color: red !important } p { color: blue !important }</style>
Inheritance
Inheritance is a way of propagating property values from parent elements to their children.
body { font-family: arial,helvetica,verdana }
All text on all elements that does not have a definite font-family property would use what is defined by the body tag; they inherit their font-family from the element they are a descendent of.
The CSS specification determines whether each property is inherited by default or not. Not all properties are inherited (e.g. margin and padding).
Important Concepts for Layout1. Block and inline display
2. Float
3. Positioning
4. z-index
Block and Inline Display
All elements naturally display as either:
Block - takes up full width available, with new line before and after (div, h1, h2, h3, h4, h6, p, ul, ol, dl, li, dt, dd, table, blockqoute, pre, form)
Inline – takes up as much width as needed, does not force new lines (span, a, b, i, u, strong, em, img, br, input)
Not Displayed (meta, title, header, script, style link)
How an element is displayed can be changed with the display property:
display: block display: inline display: none
Float
Elements are floated horizontally, not vertically.
A floated element will move as far to the left or right as it can.
Elements after the floating element will flow around it. To avoid this, use the clear property. The clear property specifies which sides of an element other floating elements are not allowed.
Elements with a float will also not have a height, unless set.
If you place several floating elements after each other, they will float next to each other if there is room.
float: left float: right clear: hidden
PositioningThe CSS positioning properties allow you to position an element. It can also place an element behind another, and specify what should happen when an element's content is too big.
It can be positioned using the top, bottom, left, and right properties only if position property is set first. They also work differently depending on the positioning method.
Static – This is the default. It is always positioned according to the normal flow of the page. Static positioned elements are not affected by the top, bottom, left, and right properties.
Fixed – fixed position is positioned relative to the browser window.
Relative – positioned relative to its normal position.
Absolute – positioned relative to the first parent element that has a position other than static. If no such element is found, the containing block
is <html>
z-indexWhen elements are positioned outside the normal flow, they can overlap other elements. The z-index property specifies the stack order of an element (which element should be placed in front of, or behind, the others).
An element can have a positive or negative stack order:
An element with greater stack order is always in front of an element with a lower stack order.
If two positioned elements overlap, without a z-index specified, the element positioned last in the HTML code will be shown on top.
You can make it dynamic by writing code to:
1. Change specific attributes of elements within your content (inline styles)
2. Add and remove CSS class names of specific elements within your content (defined in your external or embedded stylesheet)
3. Use code to create an embedded stylesheet for each page when it renders
4. Add or remove links to external stylesheets when the content renders
How do you make it Dynamic?
1. Put CSS in the header
2. Have JS place after CSS so it doesn’t block parallel stylesheet loading
3. Don’t use @import since it blocks parallel stylesheet loading
4. Serve static content from a cookieless domain. JS, CSS, images don’t need to be accompanied by cookies.
5. Use efficient CSS selectors- Avoid universal key selector- Make rules as specific as possible (class & id, over tag)- Remove redundant qualifiers- Avoid using descendant selectors (it avoids having to exam the DOM)
6. Avoid CSS expressions- They degrade rendering performance- Only support for IE5 – IE7
7. Specify image dimensions
8. Don’t resize images from their true dimensions
Basic Performance Recommendations
Advantages
1. Save HTTP request, avoid adding to object overhead
2. Save concurrent thread, browsers default to two simultaneous connections per hostname
3. HTTPS requests are simplified and performance improved
Disadvantages
4. IE5 – IE7 doesn’t support
5. Length limits (IE8 only supports 32K)
6. Base64 encoded images are roughly 33% larger than binary. Even with gzipping it is 7% larger.
7. More difficult to maintain in update in most circumstances
Inline Images with Data Urlsbackground:url(data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/ /ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExK cppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7) top left no-repeat; )