6c5b1cfea38f54f3695a1260e96fc4ce.ppt
- Количество слайдов: 72
CSS Presented by Chris Sanyk
CSS: Why take a class? Basic CSS is really, really easy to learn. n The language syntax is pretty straightforward. n Examples are everywhere. Just View Source. n The tools needed to develop CSS are free and available on any computer. n All you need is a text editor, a web browser, and a few good references. n
CSS: Why take a class: Advanced CSS can be pretty hard. n Complex CSS can be hard to work with. n Dealing with browser inconsistencies can be a pain. n Keeping up to date with CSS as it develops takes effort as well as patience. n
Why this class: n n n 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 n n NOT to become known as “the CSS guy” I have 3 goals for this class: 1. To help others learn CSS and enable them to work with it, and encourage sharing of expertise. 2. To improve my own comfort and competence with CSS so that I can grow. 3. 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. n What goals do you have?
Student/Audience Where are you at? n Silently assess yourself on a 0 -4 scale… n
Your Instructor n n n n 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. n This was limited at best, and gave rise to really messy ugly code. n The worst of it was HTML 3. 2. n
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. n 11 years later, we’re just on the cusp of HTML 5. n OK, maybe this is also a testament to the slowness of W 3 C. n Much of HTML 4’s success is owed to the success of CSS, especially CSS 2. 1. n
History Initially, HTML was all there was. n It handled both describing the structure of a document, as well as how the document should be presented. n 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. n
History n Early 90’s: n n 1993 -94: n n HTML begins to see real use. NCSA Mosaic launches WWW revolution. Birth of the modern internet. 1995: n n HTML started coming together in the early 90’s (IETF) HTML 2 1996: n CSS 1 becomes a W 3 C 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 n 1997: n n n HTML 3. 2 becomes the first version of HTML to achieve W 3 C 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 n 1998: n n CSS 2 becomes W 3 C recommendation. 1999: CSS 1 finally well-supported in the browser. n Beginning of a long period of inconsistent, incomplete support for CSS 2. 0 in the browser… and seemingly endless frustration for web developers. n
History n 2003 -04 n n n 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: n n As of 2009, W 3 C 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. n 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. n Unfortunately a fair amount of users out there aren’t on the latest versions, so 2. 1 is still your best bet. n CSS 3 extends and builds on 2. 1, so W 3 C should hurry the hell up and finalize the 2. 1 recommendation already. n
WTF, W 3 C? n n W 3 C 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. n 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. n Stability is great… but only if major problems are solved and deficiencies get addressed. n
CSS weak points n Layout n n n Flexible/fluid layout is difficult Columns Lacking Orthoganality (orthowha? ) n There’s often more than one way to achieve a desired effect, and getting different properties to work together is… screwy. n Position, Display, Float: Font sizes and dimensional units. n n n n 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 n User agent settings can mess up your style (local custom CSS, font settings, default colors, etc. ) n n 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 n Browser Support for CSS n n n Always lags behind W 3 C, at least for a while. Sometimes differs from what W 3 C specifies. (Sometimes browser devs make mistakes, sometimes W 3 C is vague. ) Some browsers also support proprietary CSS extensions (got tired of waiting for slow W 3 C). This is fine, insofar as W 3 C 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. n If you’re unlucky, badly interpreted CSS can cause your site to look broken in a particular browser (usually IE). n It’s a pain to try to support every platform; it’s sane to support open standards. n Try to stay sane. n You may not always be able to. n
Browser Support Your website will therefore look slightly different in different browsers. n Browsers ignore markup they don’t understand. n Browsers mangle markup they think they understand. n Browsers attempt to render invalid markup, but do so inconsistently. n
HTML + CSS Stop using HTML attributes for controlling presentational aspects of the web page. n Avoid using tables for layout. It’s possible, though difficult, but worth it. n Accessibility (508 & WCAG) n SEO n n Let HTML provide logical structure, and let CSS handle presentation.
Why use CSS? Advantages of CSS n In a word, reusability. CSS saves you work. Declare a style rule once, apply it everywhere you need to. n Content from one page can be brought into another without having to re-work the HTML. (In theory. ) n Reduce burden on web server by providing lightweight markup. n Easier maintenance. n HTML is more readable. n Less work to make changes to the way the site looks. n
No, really. Why should I bother to learn CSS? n n n 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. n Customization. n Do something unique. n You want to understand why the #@%* your web site doesn’t look right in $browser, and fix it. n Someone’s giving you money. n
How to use CSS n Connecting CSS to HTML Linked stylesheets n Embedded stylesheets n Inline style declarations n
Linked Stylesheets n <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. n HTML document can reference multiple. css files, and take on styling from each of them. n <link> goes in the <head> element. n
Embedded Stylesheets n <style><!-/*your CSS here*/ --></style> n 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 w 3 c-valid only in <head> but most browsers will accept it in <body> n n n
Inline style attribute n n n style=“declaration 1; declaration 2; ” <p style=“font-size: 10 pt; 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 n Properties n Values n Comments n n 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 n n 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 arecase sensitive. p { } font-size: 10 pt; color: red; div, p, h 1 {fontfamily: arial; } #head {backgroundimage: url(/case. Sentitiveurl-to/image. jpg); }
CSS Syntax: Selectors n n Universal Named element Class ID n n * div. myclass #My. ID
Combinations n Class and ID selectors can combine with elements to make a more specific rule: n p. myclass{} selects only <p class=“myclass”></p> n n n Not <p></p> Not <div class=“myclass”></div> p#My. ID{} selects only <p id=“My. ID”></p> n n Not <p></p> Not <div id=“My. ID”></div>
CSS Syntax: Selectors (advanced) n List of selectors (comma) n h 1, . myclass, . otherclass {} n Descendent selector (space) n . myclass p {} n Child selector Sibling selector ul h 1 n > + li {} p{}
Classes, IDs Use IDs for unique regions on page, since ID value must be unique for the page. n Make ID and Class names semantic, not descriptive. (e. g. , . warning -- not. red ) n
CSS Selectors n Pseudo-classes n n n : link : visited : hover : active : focus : first-child
CSS Selectors n Pseudo-element n n : 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 n Colors n The Box Model n
Font size WTF n Proportional or Absolute? n n n 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 n n Absolute units: pt px in cm mm Proportional units: ex em % (print media) Be careful/take advantage of nested proportional sizing.
Colors n n Days of 216 “web safe” colors is long gone. Descriptive color names n n n System color names (OS-specific; maybe customized by user). #xxxxxx; hex notation #xxx; n n (shorthand, less precision, saves 3 bytes of bandwidth) RGB(0 -255, 0 -255) and RGB(0 -100%, 0 -100%) n n Only 16 color names are actually W 3 C 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 n Transparency and elements n Background color n Text n Images n n Gradients
The Box Model http: //www. blogoff. es/2010/02/01/15 -articulos-de-css-para-principiantes/
Positioning static (default) n relative (offset relative to static) n absolute (offset relative to first non-static parent) n fixed – position in a fixed position within the window viewpane. Does not scroll. n n IE support spotty. ( IE >= 7)
Float and Clear n n n 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. n 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. n 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. n
Float and Clear clear tells the browser what to do with the next element that comes after a floated element. n If an element clears, it will start on the next line, not wrap around the floated element. n You can clear: left, clear: right, or clear: both. n clear applies to the element occurring aftera floated element, notto the floated element. n
Display vs. Visibility n n n 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. n Originally HTML had little/nothing else available for laying out pages. n <table> was purposed for this. n <table> is reasonably easy to design and is rendered consistently by browsers. n You don’t get weird bugs with table based layouts like you will with a <div> based layout. n
So why nix <table>? Return <table> to its intended purpose (yeah but why? ) n Allow machine readers (that’s Search Engines as well as assistive reader technologies) to read the page and interpret it correctly. n Improve your search result rankings as table contents do not score as high in SEO as do properly marked up page content. n
Getting there If you’re still in a world of <table> based layouts, you’re behind a few years. n 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. n Get used to using CSS to control all presentational aspects and get good at that. Worry about making “proper” layouts later. n
Getting there When you’re ready to transition from table to div layout… n 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! n If one does not exist exactly like what you want, find one that’s close, and tweak it. n
Getting there n n n 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… n Selector Specificity Select only what you want n Use a container and descendant selectors n n Efficiency n Re-usability n Avoid “leaking” (being too general with a selector declaration. ) n Learn the “Cascade” and take advantage of it.
Specificity and the Cascade n Selector specificity: http: //www. blogoff. es/2010/02/01/15 -articulos-de-css-para-principiantes/ n n !important trumps all (except client overrides) Conflicting rules: n n n 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. n Use comments to explain what you’ve done and why. n
Common useful CSS reset n #ID Regions with descendant selectors and unstyled children n Font size: what type of units? n CSS Box model n
Clever/Cool CSS Transparency n : hover effects n Positioning n Conditional rules n Dynamic CSS with Javascript n Combining multiple classes in one element. n CSS sprites n CSS 3 Served fonts n
CSS for other media Not just for the screen! n Printer – definitely use. n n n Mobile Devices – maybe use. n n 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. n Consider using, especially if you are concerned with accessibility.
Tips n Look at your site with CSS turned off. n 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… n and complies with it. n Validate your HTML and your CSS. n
Dealing with non-standard browser behavior n Should you? If it breaks the site. n If you’re being paid. n If you’re a perfectionist. n If you’re a masochist. n Use web server stats to decide if it makes sense. n
Understanding browser-specific issues Accessibility/Usability n Cosmetic n
If you have to address browserspecific problems… n n Try standards first. If standards-compliant CSS is handled differently by some browser… <cough>IE</cough> n n n 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. n See Useful Tools slide coming up
Handling for IE 6 n Eric asked… “What to do in IE 6 vs. everything else” n n n n 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 IE 6 for some reason… Make sure you have IE 6 around to test with. Use IE conditionals to attach an IE 6 -specific. css that overrides the standard-compliant stuff if the user agent reports itself as IE 6. Use hacks as a last resort. n Many ways to do different stuff. Google for ideas. Come up with your own if you can do better.
Recommended resources n The Web W 3 Schools. com n W 3 C. org n www. css 3. info n www. d. umn. edu/itss/support/Training/Online/we bdesign/css. html n A slew of web developer blogs, YMMV. Google & bookmark. n
A few good articles and resources n n n 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-3 column. htm
Recommended resources n Print Web Design in a Nutshell 3 rd Edition (O’Rielly) n CSS pocket reference (O’Rielly) n HTML Utopia: Designing Without Tables Using CSS ISBN 0 -9752402 -7 -7 n CSS: The Missing Manual n CSS: The Definitive Guide n
Useful Tools n Mozilla Web Developer Toolbar n Firebug n Validator extensions n Color. Zilla (color picker) n Measure. It (pixel ruler) n
Useful Tools n Safari tools n n Chrome tools n n Suggest any IE Developer Toolbar Notepad++
Awe and Inspiration n www. romancortes. com – Godlike CSS. n n Pure CSS portraits of George W. Bush, Homer Simpson, other amazing CSS marvels. Your site here! Do something extraordinary.
Homework Teach this class. n Improve this class. n Create reference examples of various CSS properties and applications. n Make a web site. n Do something creative. n Bring in a tricky problem you’re stuck on and get people to help you. n
6c5b1cfea38f54f3695a1260e96fc4ce.ppt