A CSS Survey: From Syntax to Rounded Corners
Jason Nakai & Emily Lewis
Wednesday, March 4, 2009
Jason Nakai
- Multimedia Developer for the American Society of Radiologic Technologists
- Develops distance-learning content that combines streaming media and interactive learning objects
- Specializes in web application programming, interaction design and photo-realistic vector art
Emily Lewis
- Web Designer for Pitney Bowes Business Insight
- Develops and maintains public sites, intranet, electronic newsletters and emails for marketing campaigns
- Specializes in semantic XHTML and CSS, accessibility and usability
- Writes about web design (and other topics) at A Blog Not Limited
What We'll Cover
- Emily will talk about CSS basics and best practices (she'll probably mention standards too)
- Jason will discuss his experiences working with legacy CSS, including tips and tools for making the transition to best practices
- Emily will explain some simple, but fun, features in CSS2 and CSS3
What Is CSS?
- CSS = Cascading Style Sheets
- CSS is a system of rules that tell browsers how to display HTML elements (colors, layout, fonts)
- CSS is integral to the web standard of separating content from presentation
- CSS is not a programming language (PHP, JavaScript)
- CSS is not a markup language (HTML)
- CSS rules are comprised of selectors, properties and values
The Benefits
- Ease of maintenance; updating one file vs. all pages in a site (best case scenario)
- Accessibility by separating content from presentation
- Typically cleaner and leaner documents = reduced bandwidth
- Professionalism with standards
- Better SEO
The Basics: Syntax
selector {
-
property: value;
}
- Selector
- Identifies the HTML elements the style will be applied to
- Can be just the HTML element itself (
h1
) or a class
or id
- Braces (
{}
)
- Contain the property-value pair(s)
- Property
- Declares what presentational effects you will apply to the selector, such as
font-size
, color
, position
- Colon (
:
)
- Separates the property from its value
The Basics: Syntax
- Value
- Declares the actual value of the property
- Values for color can be declared as hexadecimal (
#f000
), RGB (rgb(255,0,0)
) and names (red
)
- Values for font sizes, margins, padding, width, height can be declared as pixels, percentages, centimeters, ems and other units of measurement
- Semicolon (
;
)
- Separates multiple property-value pairs
- Good rule of thumb to conclude all CSS rules with a semicolon
h1 {
-
color: #f00;
-
font-size: 110%;
}
The Basics: Inheritance
- Uses the HTML document tree to allow some CSS properties to be passed down from parent elements to children elements
- Every element in a document will inherit all the inheritable properties from its parent except the root
html
, which has no parent
- Inherited properties in CSS can be overridden
- Some properties are not inherited (
margin
, padding
, border
, background
) so that you don't have to override them at every level where they aren't required
body {
-
color: #f00;
}
The above example uses inheritance so that all children of body
will appear in red, unless overridden with more specific style declarations.
The Basics: Cascade
- Styles cascade from one style sheet to another, so that multiple style sheets can be referenced in a document
- The cascade controls the end result when there is a conflict between multiple CSS declarations for a single element, using the following rules for the order by which styles are applied:
- Importance is determined by where a declaration is specified (browser, user, author)
- Specificity is how specific a rule’s selector is (
p
vs. p#intro
)
- Source order means that declarations that appear later in the style sheets will override those that come before them
- If two declarations have the same importance, the specificity of the rules decides which one will apply. If the rules have the same specificity, then source order controls the outcome.
The Basics: Inline Styles
You can apply styles to an element using the style
attribute:
<p style="color:#f00; font-size:110%">The quick brown fox jumped over the lazy dog's back.<p>
- Inline styles will take precedence over any other styles declared (source order in the cascade)
- Maintenance is difficult because presentation rules are scattered throughout the document
- Goes against the standard of separating content from presentation
- Can't take advantage of inheritance
The Basics: Embedded Styles
Embedded styles are placed in the head
of the document inside a style
element:
<style type="text/css" media="screen">
-
h1 {
-
color: #f00;
-
font-size: 110%;
-
}
</style>
- Allows utilization of the cascade
- Separates content from presentation
- Easier maintenance than inline; you only have to change styles in one location rather than many throughout a document
- Maintenance can still be a challenge, as you have to change styles in all documents where embedded
The Basics: External Style Sheets
External style sheets contain all your CSS rules in their own document (with a .css extension), which is referenced in HTML documents via the link
element in the head
:
<link href="styles.css" rel="stylesheet" type="text/css" media="screen" />
- Easiest maintenance: site-wide changes can be made in a single document
- Separates content from presentation
- Takes advantage of the cascade
- The accepted best practice
The Basics: @import
Style Sheets
You can also use @import
for external style sheets, which is referenced in an embedded style sheet:
<style type="text/css">
-
@import url("styles.css") screen;
</style>
- Almost the same as using a
link
reference
- Older browsers don't recognize
@import
- IE6 doesn't support media types in
@import
declarations
The Basics: media
Types
- Used to indicate on which medium a given style sheet should render
- Some CSS properties are only for a certain media (e.g.
voice-family
is for aural
)
- Other properties can be used for multiple media types, but with different values (e.g.
font-size
for screen
and print
)
- Different CSS specifications support different media types. Know what you are using.
The Basics: Referencing media
Types
If all rules in an external style sheet can be applied to a given medium, the type is declared in the link
:
<link href="print.css" rel="stylesheet" type="text/css" media="print" />
If you wish to declare specific rules within an external or embedded style sheet to apply to different media, the type is declared as part of the selector:
@print body {
-
font: 12pt Times, "Times New Roman" serif;
-
color: #000;
}
The Basics: class
Selectors
class
es are applied to HTML elements using the class
attribute
- Assigning a
class
value means that element can be presented (via CSS) differently from others of the same element
- You can use multiple (unlimited)
class
es
<p class="column featured">The quick brown fox jumped over the lazy dog's back.<p>
In the CSS, class
selectors are the name preceded by a period (.):
.column {
-
width: 50%;
-
border: 1px solid #000;
}
The Basics: id
Selectors
id
s are applied to HTML elements via the id
attribute
- Assiging an
id
means that element can be presented (via CSS) differently from others of the same element
id
s are unique; you can only use one instance of an id
in a given document
id
s also make elements to which they are assigned navigable
<p id="sidebar">The quick brown fox jumped over the lazy dog's back.<p>
In the CSS, id
selectors are the name preceded by a hash (#):
#sidebar {
-
width: 50%;
-
border: 1px solid #000;
}
The (Not So) Basics: Advanced Selectors
- Universal selectors
- Selects every element in the document to which to apply styles
-
* {
-
color: #f00;
}
- Attribute selectors
- Select elements based on their attributes and values
-
link[rel="home"] {
-
background: url(home.png) no-repeat 0 0;
}
The (Not So) Basics: Advanced Selectors
- Child selectors
- Select elements that are children (direct descendents) of other elements
-
div > strong {
-
color: #f00;
}
- Not supported in IE6 and earlier
- Descendent selectors
- Select specified elements anywhere in the hierarchy, not just children
-
div strong {
-
color: #f00;
}
The (Not So) Basics: Advanced Selectors
- Adjacent sibling selectors
- Select the sibling (same level in the hierarchy) immediately following an element
-
h1 + h2 {
-
margin:0;
}
- Not supported in IE6 and earlier
- Pseudo-element selectors
- Select information that is not available in the document tree
-
p:first-letter {
-
font-size:200%;
}
- Not supported in IE6 and earlier
The (Not So) Basics: Advanced Selectors
- Pseudo-classes
- Select specific states of elements
-
li:first-child {
-
font-style:italic;
}
- For link pseudo-classes, styles must be declared in the following order due to specificity rules:
a:link
a:visited
a:hover
a:focus
a:active
Best Practices: Grouping Selectors
For CSS efficiency and optimization, you can group selectors. So rather than:
h1 {
-
color:#f00;
}
p {
-
color:#f00;
}
Combine both selectors with the same property-value pair, separating each selector with a comma (,
):
h1, p {
-
color:#f00;
}
Best Practices: Joining Selectors
You can also join selectors for greater specificity:
p#intro.alert {
-
color:#f00;
}
Not supported in IE6 and earlier
Best Practices: Comments
- Anything contained by CSS comments is ignored by the browser
- Can be useful for troubleshooting during development
- Can appear before or within rule sets and across multiple lines
- Can be used to comment out entire rules or individual declarations
- Indicated with opening delimiter of forward slash (
/
) followed by asterisk (*
)
- Closing delimiter is an asterisk (
*
) followed by a forward slash (/
)
p {
-
color:#f00;
-
font-weight:bold;
-
/*margin: 1em 0;*/
}
Best Practices: Organization
CSS comments are also useful for organizing your CSS, particularly large CSS files. Using commented text and some visual indicators (e.g. dashes), label each section of your CSS according to what it controls:
/*---STRUCTURE/LAYOUT---*/
body{background: #666 url(/images/lilyBG.png) repeat-y 100% 0;font:small Verdana, Arial, Helvetica, sans-serif;color:#666;}
#content, #masthead{background:#fff url(/images/sidebarShadow.png) repeat-y 100% 0;float:left;width:58%;padding: 0 5% 0 2%;margin-left:24px;border-left:10px solid #fff;}
#sidebar, #primaryNav {color:#fff;float:right;width:27%;padding:0 3% 0 0;}
/*---TYPE ELEMENTS---*/
abbr, acronym{cursor:help; border-bottom:1px dotted #94a8ca;}
code {font-family:"Courier New", Courier, mono;background:#eee;}
Best Practices: Short-hand
CSS shorthand entails combining several related properties into one property to save time and file space:
- Hexadecimal colors consisting of three pairs of digits can be reduced by removing one digit from each pair:
#ff0000
becomes
#f00
- Box properties (margins, padding, border) can be combined if the values are the same for each of the four sides:
margin-top: 1em; margin-right: 1em; margin-bottom: 1em; margin-left: 1em;
becomes
margin: 1em;
Best Practices: Short-hand
- Font properties can be combined:
font-style:italic; font-weight:bold; font-size: 90%; font-family: Arial, Helvetica, sans-serif;
becomes
font: italic bold 90% Arial, Helvetica sans-serif;
- Background properties can be combined:
background-color:#f000;background-image: url(logo.png); background-repeat: no-repeat; background-position: 0 10%;
becomes
background: #f00 url(logo.png) no-repeat 0 10%;
The order of the property values in shorthand makes a difference. Follow the W3C specification.
Best Practices: Optimization
For large CSS files, it's a good idea to optimize the CSS so that file size is reduced leading to reduced bandwidth.
- Use shorthand
- Group selectors
- Get rid of extra white space
- Define declarations on a single line
Compression tools that will even further compress/optimize your CSS in terms of file size:
Best Practices: Semantics
- Semantics = meaning
- Avoid
class
es and id
s that reference presentation
- Assign values that reflect meaning/context
#secondaryNav
rather than #leftColumn
Best Practices: Validation
- Easier development and troubleshooting
- Browser consistency — both now and in the future
- Faster page loads
- Part of due diligence for accessibility
- Write it right = write it once
W3C CSS Validation Service
Best Practices: Cross-Browser Development
- Validate
- Reset your CSS by (selectively) removing default browser styles
- Develop for standards-compliant browsers (Firefox, Opera, Safari, Chrome or a browser that uses the same rendering engine as these)
- Check in IE after CSS for standards-compliant browser is complete and make any necessary workarounds (conditional comments)
- Consider dropping IE 6 support entirely
- Keep CSS hacks to a minimum; a last resort only
Legacy CSS: First Steps
When inheriting existing CSS from another developer (who may or may not have followed best practices):
- Review the markup
- Review the CSS
- Organize the CSS (e.g., alphabetically, functionality, type …)
Legacy CSS: Editing
- Remove the ill-formed, non-functioning rules (e.g., missing braces, missing semicolons, non-existent properties)
- Eliminate redundant rules by grouping selectors (e.g,
h1, .h1, #h1 {blah:blahblah;}
)
Legacy CSS: DustMe Selectors
DustMe Selectors is a Firefox plugin from SitePoint that helps weed out unused rules:
- Checks for unused selectors
- Can spider a site using a site map
- May require some tweaking of your site map
Legacy CSS: Firebug
Firebug is a Firefox plugin that inspects and changes CSS directly in the browser:
- Identify & fix the remaining ill formed but functioning rules
- Firebug Lite is available for other browsers
Legacy CSS: Condense & Organize
- Convert to shorthand where applicable
- Organize properties (alphabetically)
- Organize rules by functionality
- Add CSS comments to give meaning to your groupings
Using Dreamweaver With Legacy CSS: Convert Inline to Embedded
- Right-click inline styled elements and choose CSS Styles > Convert Inline CSS to Rule
- Choose what you want to convert it to & name it if applicable
- Recommend creating a new
class
unless you know that you can reuse an existing style
- Finally, choose Create Rule in "The head of this document"
- Rinse & repeat
Using Dreamweaver With Legacy CSS: Move Embedded to External
- Expand the CSS Panel
- Choose the CSS Styles tab
- Make sure the Select All tab is active
- Expand the "style" node
- Highlight all rules
- Right-click & choose Move CSS Rules…
- Choose a style sheet to add them to or create a new one
- Click OK
These steps move embedded to external, but the style
element remains in the head
. Clean this up.
Legacy CSS Is Tamed
- You now have gathered all your CSS rules in to one place!
- You may need to go back into your style sheet & clean up duplicates.
- As you move forward, keep your CSS tidy & organized.
Turning the Tables on table
s
- Ease into it
- Don't alienate your team in your quest for standards
- This transition comes with a learning curve
- Find a way to incorporate it into your current workflow
- Provide training or learning resources for your team
table
Transition: table
-Based & CSS Layout
- Strip content of all formatting
- Organize based on flow and hierarchy
- Add meaningful/semantic markup
- Add CSS
- Wrap in a
table
- Plug into page
table
Transition: Build a Library of Templates & Containers
- Make it easy to implement
- Add efficiency to workflow
- Decrease turnaround time
- Training through action
Fun With CSS2: Generated Content
- The Markup:
<p>Generated content is supported by <a href="http://www.getfirefox.com">Firefox</a>, <a href="http://www.apple.com/safari/download">Safari 3</a>, <a href="http://www.opera.com/">Opera</a> and <a href="http://www.google.com/chrome">Chrome</a>.</p>
- The CSS:
-
@print a:after {
-
content:" ("attr(href)") "}
}
Generated content in action on A Blog Not Limited: see "All Tags" & "All Dates" links in sidebar. The > symbol is generated content via {content: " >";}
Fun With CSS2: Generated Content In Action
See "All Tags" & "All Dates" links in sidebar on A Blog Not Limited:
The > symbol is generated content via:
{content: " >";}
Fun With CSS2: Text Shadows
- The Markup:
<p>Text shadow works in Safari 3 and Opera.</p>
- The CSS:
-
p {
-
text-shadow: 1px 1px 1px #000;
}
Fun With CSS2: Text Shadow In Action
See see all headings, as well as sidebar and footer content on A Blog Not Limited:
All have text shadows via:
{text-shadow: #999 1px 1px 2px;}
CSS3 You Can Use Now: Gradient Borders
- The Markup:
<div class="featured"><p>Gradient borders only work in Mozilla/Firefox.</p></div>
- The CSS:
-
.featured {
-
padding: 10px;
-
border: 8px solid #eee;
-
-moz-border-bottom-colors: #555 #666 #777 #888 #999 #aaa #bbb #ccc;
-
-moz-border-top-colors: #555 #666 #777 #888 #999 #aaa #bbb #ccc;
-
-moz-border-left-colors: #555 #666 #777 #888 #999 #aaa #bbb #ccc;
-
-moz-border-right-colors: #555 #666 #777 #888 #999 #aaa #bbb #ccc;
}
CSS3 You Can Use Now: Rounded Corners
- The Markup:
<div class="featured"><p>Rounded corners only work in Firefox, Safari and Chrome.</p></div>
- The CSS:
-
.featured {
-
padding: 10px
-
border: 1px solid #666
-
-moz-border-radius: 5px;
-
-webkit-border-radius: 5px;
}
Fun With CSS2: Rounded Corners In Action
See "box" containers on PBBI Insights:
All have opposing rounded corners via:
{border: 1px solid #d9e3ed;
border-radius: 1em 0;
-moz-border-radius-topleft: 1em;
-moz-border-radius-bottomright: 1em;
-webkit-border-top-left-radius: 1em;
-webkit-border-bottom-right-radius: 1em;}
CSS3 You Can Use Now: Opacity via RBGa
- The Markup:
<div class="featured"><p>RGBa is only supported by Firefox, Safari and Chrome.</p></div>
- The CSS:
-
.featured {
-
padding: 10px
-
border: 2px solid rgb(0,0,255);
-
background-color: rgba(0, 0, 255, 0.4);
}
For similar visual results (but more CSS), the opacity
property is supported by Firefox, Safari, Chrome and Opera
CSS3 You Can Use Now: Opacity In Action
See 24 Ways:
Tons of opacity via RGBa. Too many to list … just view the CSS source.
CSS3 You Can Use Now: Mimic Double Borders with outline-offset
- The Markup:
<div class="featured"><p>Outline offset is supported by Firefox, Safari and Chrome.</p></div>
- The CSS:
-
.featured {
-
padding: 10px
-
border: 2px solid #333;
-
outline: 2px solid #666;
-
outline-offset: 3px;
}
Even More CSS3 You Can Use Now
Thank You!
Questions, comments?