CSS Presented by Chris Sanyk CSS: Why take a class? Basic CSS is really, really easy to learn. The language syntax is pretty straightforward. Examples are everywhere. Just ViewSource. The tools needed to develop CSS are free and available on any computer. All you need is a text editor, a web browser, and a few good references. CSS: Why take a class: Advanced CSS can be pretty hard. Complex CSS can be hard to work with. Dealing with browser inconsistencies can be a pain. Keeping up to date with CSS as it develops takes effort as well as patience. Why this class: Most classes I’ve seen or taken have focused on by-thebook basics. I find those are easy enough to pick up on your own. What people really need from a class on CSS is to acquire “street smarts” so they can avoid the traps that ordinarily are discovered and defeated through experience. Hopefully you’ll come out of this with a solid understanding of fundamentals, how to do the basic stuff effectively and efficiently, and maybe a few cool tricks. My Goals NOT to become known as “the CSS guy” I have 3 goals for this class: 1. 2. 3. To help others learn CSS and enable them to work with it, and encourage sharing of expertise. To improve my own comfort and competence with CSS so that I can grow. To build a course foundation that can be re-used by any competent instructor, and improved upon in successive teachings, and potentially packaged and sold as a product. What goals do you have? Student/Audience Where are you at? Silently assess yourself on a 0-4 scale… Your Instructor Overall: 3 Basics: 4 CSS for HTML <form> elements: 2 Browser compatibility: 2 CSS positioning: 2 CSS 3: 1-2 Probably some people in the room know more. Let’s collaborate on making the class better! History Before CSS, HTML used a combination of <elements> and attributes=“” for controlling the presentation of a web page. This was limited at best, and gave rise to really messy ugly code. The worst of it was HTML 3.2. History HTML 4 (and XHTML 1), which has been around since 1999, was a major cleanup of this mess, and was very successful in many ways. 11 years later, we’re just on the cusp of HTML 5. OK, maybe this is also a testament to the slowness of W3C. Much of HTML 4’s success is owed to the success of CSS, especially CSS 2.1. History Initially, HTML was all there was. It handled both describing the structure of a document, as well as how the document should be presented. Presentational aspects of early HTML were fairly limited, both in terms of the effects that could be achieved, and how they were applied to a document element. History Early 90’s: 1993-94: HTML begins to see real use. NCSA Mosaic launches WWW revolution. Birth of the modern internet. 1995: HTML started coming together in the early 90’s (IETF) HTML 2 1996: CSS 1 becomes a W3C recommendation in 1996. It is fairly basic and not widely supported by web browsers right away. No one can use it in the real world. History 1997: HTML 3.2 becomes the first version of HTML to achieve W3C recommendation status. Previously, HTML was just developed by various people and groups. HTML 3.2 mostly consolidated a bunch of proprietary extensions to HTML that had been created by Netscape, Microsoft, and others. Because browsers don’t support CSS well, and because CSS 1 is so limited, a host of presentational HTML elements and attributes are incorporated into the 3.2 spec, turning it into a horrid mess. HTML 3.2 code is bloated, ugly, and hard to read as content becomes buried in a mess of presentational markup. History 1998: CSS 2 becomes W3C recommendation. 1999: CSS 1 finally well-supported in the browser. Beginning of a long period of inconsistent, incomplete support for CSS 2.0 in the browser… and seemingly endless frustration for web developers. History 2003-04 Browsers now have decent support for much of CSS 2, and continue to improve. As of 2008, no browser had fully supported the CSS 2.0 specification. 2009: As of 2009, W3C has only managed to advance CSS 2.1 to “candidate recommendation” status. Despite this, CSS 2.1 is the current dominant de-facto “standard”, and has been reasonably well-supported by browsers since around 2005-6. Sadly, well-supported does not mean “perfectly” or “completely.” Today CSS 3 is emerging. Parts of it are already widely supported by current versions of major browsers. Unfortunately a fair amount of users out there aren’t on the latest versions, so 2.1 is still your best bet. CSS 3 extends and builds on 2.1, so W3C should hurry the hell up and finalize the 2.1 recommendation already. WTF, W3C? W3C risks making itself irrelevant if they can’t release recommendations more quickly. WWW currently has a strong foundation in open standards. This should not be taken for granted. If these standards do not evolve to meet the needs of web developers, we run the risk of losing this openness. Proprietary innovation could overtake open standards. WWW++ could end up being built from proprietary tech such as Flash and Silverlight. On the other hand… Getting 10 (well, OK, more like 5) years use out of something is pretty nice. Not having to learn the latest version every year or so frees you from being stuck in the perpetual learning curve, and allows you to get good. Stability is great… but only if major problems are solved and deficiencies get addressed. CSS weak points Layout Flexible/fluid layout is difficult Columns Lacking Orthoganality (orthowha?) There’s often more than one way to achieve a desired effect, and getting different properties to work together is… screwy. Position, Display, Float: Font sizes and dimensional units. Which do you use, when? How do they work together? Selectors are unable to ascend (there’s no “parent of ” selector.) Vertical control (lack thereof, especially with centering). No way to express calculated values. No explicit scope declaration. CSS weak points User agent settings can mess up your style (local custom CSS, font settings, default colors, etc.) This is actually a not a weak point, as it means that ultimately the client has control over their preferences. But this can drive designers and product owners nuts because they don’t have absolute control. Even if the standards remain stable, if the browsers are constantly going through updates and their support of CSS changes over time, you’re shooting at a moving target. The Browser Browser Support for CSS Always lags behind W3C, at least for a while. Sometimes differs from what W3C specifies. (Sometimes browser devs make mistakes, sometimes W3C is vague.) Some browsers also support proprietary CSS extensions (got tired of waiting for slow W3C). This is fine, insofar as W3C does not own CSS; that’s why they’re called recommendations. It does, however, inconvenience web developers when browsers implement CSS support differently. Each browser has a “default” stylesheet that it uses for determining what plain HTML looks like. And each is somewhat different. Browser Support Bottom line: Browser support for CSS is inconsistent. If you’re unlucky, badly interpreted CSS can cause your site to look broken in a particular browser (usually IE). It’s a pain to try to support every platform; it’s sane to support open standards. Try to stay sane. You may not always be able to. Browser Support Your website will therefore look slightly different in different browsers. Browsers ignore markup they don’t understand. Browsers mangle markup they think they understand. Browsers attempt to render invalid markup, but do so inconsistently. HTML + CSS Stop using HTML attributes for controlling presentational aspects of the web page. Avoid using tables for layout. It’s possible, though difficult, but worth it. Accessibility (508 & WCAG) SEO Let HTML provide logical structure, and let CSS handle presentation. Why use CSS? Advantages of CSS In a word, reusability. CSS saves you work. Declare a style rule once, apply it everywhere you need to. Content from one page can be brought into another without having to re-work the HTML. (In theory.) Reduce burden on web server by providing lightweight markup. Easier maintenance. HTML is more readable. Less work to make changes to the way the site looks. No, really. Why should I bother to learn CSS? Do you really need to know CSS in order to make web sites? Mmmm… maybe not. Consider: do you want to be a codemonkey, or do you want to author content? CMS frameworks do a lot of monkey work for you. They are good. Use them. Even if you’re a codemonkey. Especially if you’re a codemonkey. Use/modify existing templates/themes/etc. Concentrate on your message, and having something interesting to say. Why learn CSS? Control. Customization. Do something unique. You want to understand why the #@%* your web site doesn’t look right in $browser, and fix it. Someone’s giving you money. How to use CSS Connecting CSS to HTML Linked stylesheets Embedded stylesheets Inline style declarations Linked Stylesheets <link rel="stylesheet" type="text/css" href=“mystyle.css" /> The preferred way. An external .css file contains your CSS code, and can be referenced by multiple HTML documents. Maximizes reusability. HTML document can reference multiple .css files, and take on styling from each of them. <link> goes in the <head> element. Embedded Stylesheets <style><!-/*your CSS here*/ --></style> Not very reusable, since the CSS rules can only be utilized by the HTML document it is embedded within. Useful in the event that you need to make sure the HTML file stays with its CSS markup. Devious “css injection” possibilities… (don’t allow <style> tag in web forums, or users will do bad things to your site.) <style> is w3c-valid only in <head> but most browsers will accept it in <body> Inline style attribute style=“declaration1; declaration2;” <p style=“font-size:10pt; color:red;”> Nearly any HTML element can take a style attribute Inline styles are more specific; that is, they will override rules declared in external or embedded stylesheets. Inline styles are good for ad hoc or temporary solutions, but at the expense of the re-usability of the HTML/content. They’re fine for posting comments to discussion boards. CSS Syntax Selectors Properties Values Comments property:value = declaration. ; = separator. Single declarations or the end declarations don’t technically need ; it is a separator, not a terminator. Selector {property: value;} /* Comment */ CSS Syntax Whitespace doesn’t matter (with one important exception.) Format for readability, try to be consistent. CSS itself is not case sensitive. Treat it like it is anyway; some browsers seem to implement it as case sensitive, and urls referencing resources in CSS are case sensitive. p { font-size:10pt; color: red; } div, p, h1 {fontfamily: arial;} #head {backgroundimage: url(/caseSentitiveurl-to/image.jpg);} CSS Syntax: Selectors Universal Named element Class ID * div .myclass #MyID Combinations Class and ID selectors can combine with elements to make a more specific rule: p.myclass{} selects only <p class=“myclass”></p> Not <p></p> Not <div class=“myclass”></div> p#MyID{} selects only <p id=“MyID”></p> Not <p></p> Not <div id=“MyID”></div> CSS Syntax: Selectors (advanced) List of selectors (comma) h1, .myclass, .otherclass {} Descendent selector (space) .myclass p {} Child selector Sibling selector ul > li {} h1 + p{} Classes, IDs Use IDs for unique regions on page, since ID value must be unique for the page. Make ID and Class names semantic, not descriptive. (e.g., .warning -- not .red ) CSS Selectors Pseudo-classes :link :visited :hover :active :focus :first-child CSS Selectors Pseudo-element :first-line :first-character :after :before CSS 2.1 Selector Summary Pattern Meaning * Matches any element. E Matches any E element (i.e., an element of type E). E F Matches any F element that is a descendant of an E element. E > F Matches any F element that is a child of an element E. E:first-child Matches element E when E is the first child of its parent. E:link E:visited Matches element E if E is the source anchor of a hyperlink of which the target is not yet visited (:link) or already visited (:visited). E:active E:hover E:focus Matches E during certain user actions. E:lang(c) Matches element of type E if it is in (human) language c (the document language specifies how language is determined). E + F Matches any F element immediately preceded by a sibling element E. E[foo] Matches any E element with the "foo" attribute set (whatever the value). E[foo="warning "] Matches any E element whose "foo" attribute value is exactly equal to "warning". E[foo~="warnin g"] Matches any E element whose "foo" attribute value is a list of space-separated values, one of which is exactly equal to "warning". E[lang|="en"] Matches any E element whose "lang" attribute has a hyphen-separated list of values beginning (from the left) with "en". DIV.warning Language specific. (In HTML, the same as DIV[class~="warning"].) E#myid Matches any E element with ID equal to "myid". Other CSS Fundamentals Font size and dimensional units Colors The Box Model Font size WTF Proportional or Absolute? Each has pros and cons; there is no ideal perfect method. Proportional units are usually the way to go. Absolute units are useful in some cases Absolute units: pt px in cm mm Proportional units: ex em % (print media) Be careful/take advantage of nested proportional sizing. Colors Days of 216 “web safe” colors is long gone. Descriptive color names System color names (OS-specific; maybe customized by user). #xxxxxx; hex notation #xxx; (shorthand, less precision, saves 3 bytes of bandwidth) RGB(0-255,0-255,0-255) and RGB(0-100%,0-100%,0-100%) Only 16 color names are actually W3C standard. +124 (for a total of 140) more color names (orig. Netscape) are widely supported. But does each browser truly render them all identically? These can’t be relied upon absolutely for all user agents; some may not support them at all. (why bother?) Seem to be popular in generated code for some reason. If using number values, it can be helpful to comment with a name or description of the color. End user monitors are very likely not color calibrated, accuracy is not critical. Colors “Transparent” named color Transparency and elements Background color Text Images Gradients The Box Model http://www.blogoff.es/2010/02/01/15-articulos-de-css-para-principiantes/ Positioning static (default) relative (offset relative to static) absolute (offset relative to first non-static parent) fixed – position in a fixed position within the window viewpane. Does not scroll. IE support spotty. ( IE >= 7) Float and Clear float and clear are not implemented consistently among all leading browsers. This is why they are sometimes more of a pain than they should be. Blame IE for its bad behavior with float. Usually can be fixed with an extra <div> to wrap the element and float the <div>. Floated elements do not influence the height of their parent. Beware overflowing floats. Use 0-height <div> with Clear after a overflowing Floated element if you need to fix it. Float and Clear float:left or float:right takes the element out of normal flow, and wraps other content around it. If the floated HTML element does not have a defined width, float will not work properly unless you provide a width value. (<p>, <blockquote>, <div>, etc.) The floated element’s width has to be narrower than its parent. Float and Clear clear tells the browser what to do with the next element that comes after a floated element. If an element clears, it will start on the next line, not wrap around the floated element. You can clear:left, clear:right, or clear:both. clear applies to the element occurring after a floated element, not to the floated element. Display vs. Visibility Be aware of distinction between display:none and visibility:hidden. Display:none collapses. Visibility:hidden takes up space. HTML De-<table>-fication <table> was always intended for tabular data. Originally HTML had little/nothing else available for laying out pages. <table> was purposed for this. <table> is reasonably easy to design and is rendered consistently by browsers. You don’t get weird bugs with table based layouts like you will with a <div> based layout. So why nix <table>? Return <table> to its intended purpose (yeah but why?) Allow machine readers (that’s Search Engines as well as assistive reader technologies) to read the page and interpret it correctly. Improve your search result rankings as table contents do not score as high in SEO as do properly marked up page content. Getting there If you’re still in a world of <table> based layouts, you’re behind a few years. If you’re a complete newbie and are just getting the hang of HTML+CSS and aren’t doing anything serious, use <table> layouts for a while like training wheels. Get used to using CSS to control all presentational aspects and get good at that. Worry about making “proper” layouts later. Getting there When you’re ready to transition from table to div layout… Hopefully you’re using a framework or CMS that does it for you already and you don’t have to worry. Find a template or whatever and go! If one does not exist exactly like what you want, find one that’s close, and tweak it. Getting there If not using a CMS or framework, work into it. Start simple. Re-do your layout iteratively. Challenge yourself to use as FEW tables as possible. (Most <table> layouts use NESTED tables. The more nesting, the worse for accessibility.) Work on eliminating the inner tables first. Stick with fixed-width layouts until you’re really good. Fluid layouts are harder & not necessarily better. Using CSS Effectively… Selector Specificity Select only what you want Use a container and descendant selectors Efficiency Re-usability Avoid “leaking” (being too general with a selector declaration.) Learn the “Cascade” and take advantage of it. Specificity and the Cascade Selector specificity: http://www.blogoff.es/2010/02/01/15-articulos-de-css-para-principiantes/ !important trumps all (except client overrides) Conflicting rules: Top score wins. Tie goes to last declared. Rules that don’t conflict accumulate. …And Efficiently Use lists of selectors to consolidate like blocks code. Use comments to explain what you’ve done and why. Common useful CSS CSS reset #ID Regions with descendant selectors and unstyled children Font size: what type of units? CSS Box model Clever/Cool CSS Transparency :hover effects Positioning Conditional rules Dynamic CSS with Javascript Combining multiple classes in one element. CSS sprites CSS3 Served fonts CSS for other media Not just for the screen! Printer – definitely use. Mobile Devices – maybe use. Get rid of the “printable view” link. Test by printing to PDF or Print Preview; avoid wasting paper. Hard to test for. Mobile devices vary widely, and most are still bad. Aural – for text-to-speech technologies. Consider using, especially if you are concerned with accessibility. Tips Look at your site with CSS turned off. If it’s readable and the placement of stuff makes sense, that’s a good sign that your HTML doesn’t suck. Be sure your HTML uses a doctype declaration… and complies with it. Validate your HTML and your CSS. Dealing with non-standard browser behavior Should you? If it breaks the site. If you’re being paid. If you’re a perfectionist. If you’re a masochist. Use web server stats to decide if it makes sense. Understanding browser-specific issues Accessibility/Usability Cosmetic If you have to address browserspecific problems… Try standards first. If standards-compliant CSS is handled differently by some browser… <cough>IE</cough> use a conditional stylesheet to handle it, rather than “one size fits all” code. Try to keep your browser-specific fixes short, isolated, commented, and tidy. Use tools to hone in on the problem. See Useful Tools slide coming up Handling for IE6 Eric asked… “What to do in IE6 vs. everything else” Tie a rock to it and drop it off the continental shelf Seriously, it’s 2010 FFS. Serve a warning to the user that their browser is unsafe for web browsing and recommend they upgrade use something else. If you absolutely must support IE6 for some reason… Make sure you have IE6 around to test with. Use IE conditionals to attach an IE6-specific .css that overrides the standard-compliant stuff if the user agent reports itself as IE6. Use hacks as a last resort. Many ways to do different stuff. Google for ideas. Come up with your own if you can do better. Recommended resources The Web W3Schools.com W3C.org www.css3.info www.d.umn.edu/itss/support/Training/Online/we bdesign/css.html A slew of web developer blogs, YMMV. Google & bookmark. A few good articles and resources http://jontangerine.com/log/2007/09/theincredible-em-and-elastic-layouts-with-css http://www.bigbaer.com/css_tutorials/css.imag e.text.wrap.htm http://www.bigbaer.com/css_tutorials/css.scale. image.html.tutorial.htm http://riddle.pl/emcalc/ http://matthewjamestaylor.com/blog/perfect-3column.htm Recommended resources Print Web Design in a Nutshell 3rd Edition (O’Rielly) CSS pocket reference (O’Rielly) HTML Utopia: Designing Without Tables Using CSS ISBN0-9752402-7-7 CSS: The Missing Manual CSS: The Definitive Guide Useful Tools Mozilla Web Developer Toolbar Firebug Validator extensions ColorZilla (color picker) MeasureIt (pixel ruler) Useful Tools Safari tools Chrome tools Suggest any IE Suggest any IE Developer Toolbar Notepad++ Awe and Inspiration www.romancortes.com – Godlike CSS. Pure CSS portraits of George W. Bush, Homer Simpson, other amazing CSS marvels. Your site here! Do something extraordinary. Homework Teach this class. Improve this class. Create reference examples of various CSS properties and applications. Make a web site. Do something creative. Bring in a tricky problem you’re stuck on and get people to help you.