RSS
 

Posts Tagged ‘CSS’

100 Exceedingly Useful CSS Tips and Tricks

06 Dec

100 Exceedingly Useful CSS Tips and Tricks

You can never have too much of a good thing–and two good things we rely on in our work are tips and tricks. Nuggets of information, presented clearly and succinctly, help us build solutions and learn best practices. In a previous article, we shared a jam-packed list of 250 quick web design tips. It seems only right to continue the trend by showcasing 100 fresh–and hopefully useful–CSS tips and tricks.

General

Not everything in this list was easy to categorize. All of the tips that are relevant and worthy of mention but don’t cleanly fit into a category are listed in this section.

GeneralConditional comments have been a godsend for resolving Internet Explorer inconsistencies.

1 It’s critical when working with CSS to be aware of the various properties at your disposal and how to use them correctly.

2 Using a good editor can increase productivity. Syntax highlighting and auto-complete functionality (plus validation and code references) make life easy. Check out Notepad++, Coda, and don’t discount Dreamweaver CS’s code view until you try it.

3 In many ways, experimentation is the mother of innovation. Give yourself time to play; trial and error will help you learn and memorize techniques quickly. Check out these CSS3 experiments, for inspiration: How to Create Inset Typography with CSS3, Semantic CSS3 Lightboxes, and 10 Interesting CSS3 Experiments and Demos.

4 Enable Gzip compression server-side whenever possible; it shrinks the size of files such as CSS and JavaScript without removing any of the content.

5 Caching will conserve bandwidth for visitors and account for much faster speeds. Take advantage of it whenever you can. Learn about optimizing browser caching.

6 Whitespace is important for CSS readability. Using whitespace to format your stylesheet adds bytes to the file size, but it’s made up for in increased readability.

7 Avoid using inline code (in either elements using the style attribute or in the HTML document within <style> tags), and put them instead in your external stylesheets. It’ll be easier to maintain and also takes advantage of browser caching.

8 Whatever method you use to lay code out, be consistent. You’ll avoid potential problems such as misinterpretation.

9 Conditional comments can help you target versions of Internet Explorer for style. Filtering vendor-specific code isn’t ideal, and comments are safer than ugly hacks.

10 This tip is slightly controversial, but I recommend using a single stylesheet rather than multiple ones. It reduces the number of HTTP requests and improves maintainability, giving your site a performance gain. This is a tip supported by Google Page Speed guidelines.

11 When there are conflicting style rules, style rules that are later down the stylesheet supersedes the ones that come before it. Thus, put mission-critical declarations at the end, where they won’t be in danger of being overridden by other styles.

12 If you encounter a bug and can’t determine its cause, disable CSS (using something like Firebug or the Web Developer add-on) or simply comment out all of the styles, and then bring selectors back one by one until the fault is replicated (and thus identified).

13 Make sure your code works in various browsers. Check it against the latest versions of the top five: Internet Explorer, Firefox, Chrome, Safari and Opera.

14 Additionally, ensure that your code will degrade gracefully when CSS is disabled in the user’s browser. To test this, either turn styles off in every browser or use a text browser such as Lynx.

15 Ensuring that your code degrades gracefully is obviously important, but many people forget that some visitors will have a dodgy browser or have styles turned off, so check that your fallbacks work.

16 Every browser has a built-in debugger. In IE and Firefox you can get to the inspector by hitting F12; for Chrome, Safari and Opera, press Ctrl + Shift + I.

17 Browser emulators can’t replace the real thing, so use a real or virtualized edition of a browser or device.

18 Did you know that PHP code can create dynamic CSS files? Here’s a tutorial on that. Just give the file a .php extension and ensure that the file declares the document header with a text/css content type.

19 Naming CSS files can be tricky. One of the best ways to approach the task is to keep file names short and descriptive, like screen.css, styles.css or print.css.

20 Any code or process you create is valuable, and recycling what you’ve produced for other projects is not a bad thing: pre-existing code is a great timesaver, and this is how JavaScript and CSS frameworks are born.

21 While comments in CSS files can assist other people who read or maintain them, avoid writing comments unless they are required. Comments consume bandwidth. Write CSS in a self-explanatory manner by organizing them intuitively and using good naming conventions.

22 If you’re struggling to remember what’s available in CSS (or even CSS3), get some cheat sheets. They’re simple and can help you get used to the syntax. Here are some excellent CSS cheat sheets: CSS Cheat Sheet (Added Bytes), CSS Shorthand Cheat Sheet (Michael Leigeber), CSS 2.1 and CSS 3 Help Cheat Sheets (PDF) (Smashing Magazine).

23 Bad code breaks more websites than anything else. Validate your code by using the free, web-based W3C CSS Validation Service to reduce potential faults.

24 Vendor-specific CSS won’t validate under the current W3C specifications (CSS2.1), but could give your design some useful enhancements. Plus, if you’d like to use some CSS3 for progressive enhancement, there’s no way around using them in some instances. For example, the -webkit-transform and -moz-transform property was used to progressively enhance these CSS3-animated cards for users using Safari, Chrome, and Mozilla Firefox.

25 Keep multiple CSS files in a single directory, with an intuitive name such as css/. If your website has hundreds of pages, maintainability and information architecture are vital.

At-rules, Selectors, Pseudo-classes, and Pseudo-elements

Targeting your code for styling is one of the primary functions of CSS. Whether you’re trying to make your code mobile-friendly, printer-friendly or just good old screen-friendly, you’ll be following certain conventions. Ensuring that styles aren’t in conflict, using CSS inheritance correctly and triggering actions in response to events (such as hovering) are all part of the CSS package. This section is dedicated to useful tips related to conventions.

At-rules, Selectors, Pseudo-classes, and Pseudo-elementsWith CSS3 media queries, designing for non-standard experiences has become easier.

26 Be careful when using the media attribute in your HTML declaration for an external CSS file. You might be unable to use media queries to better provide pre-cached alternative visuals.

27 If you find elements that use the same properties and values, group them together by using a comma (,) to separate each selector. This will save you from repetition.

For example, if you have the following:

h1 { color:#000; }
h2 { color:#000; }

Combine them as such:

h1, h2 { color:#000; }

28 Printer-friendly stylesheets are very important if you want to save your visitors’ ink and paper. Use the @media print at-rule, and remove anything that isn’t necessary on the printed page.

29 Accessibility also has to do with how the written word is spoken. The aural (now deprecated in CSS) and speech media queries can improve usability for screen readers.

30 Unfortunately, the handheld media query in CSS isn’t widely supported. If you want your website to work on mobile devices, don’t depend on it to serve the correct visuals to mobile devices.

31 Take the time to eliminate duplicate references and conflicts in your CSS. It will take some time, but you’ll get a more streamlined render and fewer bytes in your files.

32 When working with mouse hover events, deal with the (1) :link pseudo-class, then (2) :visited, then (3) :hover and finally (4) :active — in that order. This is necessary because of the cascade.

33 Making a website work well on Apple iOS devices is straightforward: to scale your design, just use CSS3 media queries with the appropriate min-width and max-width values. Here’s a tutorial for that.

34 Make the most of CSS inheritance by applying required styles to parent elements before applying them to the children. You could hit several birds with one stone.

35 You can apply multiple classes to an element with space separation, which is great if you want to share properties with numerous elements without overwriting other styles.

36 If you don’t want to deal with IE6’s conditional comment quirks–they require a separate CSS file–then you can use the star hack (* html) selector, which is clean and validates.

37 HTML tooltips are fine for plain text, but the :hover pseudo-class for CSS tooltips gives you more options for showing styled content. Check out this tutorial on how to create CSS-only tooltips.

38 Using attribute selectors, you can add icons or unique styles depending on the file type you link to in an anchor. Here’s an example with which you can add style to a PDF link: a[href$='.pdf].

39 You can also use attribute selectors to target a specific pseudo-protocol such as mailto or skype: [href^="skype:"].

40 Rendering CSS takes time, and listing selectors adds bytes. Reduce the workload of a renderer by using only the selectors you require (an id is better than many child references).

41 Not everyone will agree with this, but I recommend writing every "custom" selector down as a class (before making it an id) to help eliminate duplicate entries.

42 When structuring your CSS file by selectors, the convention is to list elements, then classes (for common components) and finally any ids (for specific, unique styles).

43 Naming conventions for selectors are important. Never use names that describe physical attributes (such as redLink), because changing the value later could render the name inappropriate.

44 Case sensitivity relates to naming conventions. Some people use dashes (e.g. content-wrapper) or underscores (i.e. content_wrapper), but I highly recommend using camel case (e.g. contentWrapper) for simplicity.

45 The universal selector (*) is used widely in CSS reset mechanisms to apply specific properties to everything. Avoid it if you can; it increases the rendering load.

46 With CSS3 media queries, you can easily target the orientation of a viewport with portrait or landscape mode. This way, handheld devices make the most of their display area.

47 Apple’s devices are unique in that they support a <meta name="viewport"> tag, which has stylistic value attached to it. You can use this to force the screen to zoom at a fixed rate of 100%.

48 The two CSS3 pseudo-elements, :target and :checked have great potential. They apply their designated style only to certain events and can be useful as hover event alternatives.

49 Embedding content in CSS is a unique way to give anchor links some description in printer-friendly stylesheets. Try them with the ::before or ::after pseudo-elements.

50 IDs can serve a dual purpose in CSS. They can be used to apply styling to a single element and to act as an anchoring fragment identifier to a particular point on the page.

Layout and the Box Model

When we’re not selecting elements for styling, we spend a lot of time figuring out how things should appear on the page. CSS resets and frameworks help us with consistency, but we should know how to correctly apply styles such as positioning and spacing. This cluster of useful tips relates to the aspects of CSS that fundamentally affect how the components of a website appear and are positioned.

Positioning plays a critical role in the readability of information and should not be ignored.

51 Many designs are focused on grids and the rectangular regions of the viewport. Instead, create the illusion of breaking out of the box for added effect.

52 If margin: auto; on the left and right sides isn’t getting you the central point you desire, try using left: 50%; position: absolute; and a negative margin half the width of the item.

53 Remember that the width of an item constitutes the specified width as well as the border width and any padding and margins. It’s basically a counting game!

54 Another controversial tip here: don’t use CSS resets. They are generally not needed if you take the time to code well.

55 A CSS framework such as Blueprint or YUI Grids CSS might assist you speed up development time. It’s a bit of extra code for the user to download, but it can save you time.

56 Remember that Internet Explorer 6 does not support fixed positioning. If you want a menu (or something else) to be sticky, it’ll require some hacks or hasLayout trickery.

57 Whitespace in web designs is amazing; don’t forget it. Use margins and padding to give your layout and its content some breathing room. You’ll create a better user experience.

58 If one thing overcomplicates the task of scaling a design the way you want, it’s using inconsistent measurements. Standardize the way you style.

59 Different browsers have different implementations; visually impaired users may want to zoom in, for example. Give your layout a quick zoom-test in web browsers to ensure the style doesn’t break!

60 Most browsers can use box-shadow without extra HTML. IE can do the same with filter: progid:DXImageTransform.Microsoft.Shadow(color='#CCCCCC', Direction=135, Strength=5);

61 Rounded corners aren’t as difficult to make as they used to be. CSS3 lets you use the border-radius property to declare the curvature of each corner without surplus mark-up and the use of images.

62 One disadvantage of liquid layouts is that viewing on a large screen makes content spill across the viewport. Retain your desired layout and its limits by using min-width and max-width.

63 WebKit animations and transitions might work only in Safari and Chrome, but they do add a few extra unique, graceful flourishes worthy of inclusion in interactive content.

64 If you want to layer certain elements over one another, use the z-index property; the index you assign will pull an element to the front or push it behind an item with a higher value.

65 Viewport sizes aren’t a matter of resolution. Your visitors may have any number of toolbars, sidebars or window sizes (e.g. they don’t use their browsers maximized) that alter the amount of available space.

66 Removing clutter from an interface using display:none might seem like a good idea, but screen-reader users won’t be able to read the content at all.

67 Be careful with the overflow CSS property when catering to touch-screen mobile devices. The iPhone, for example, requires two fingers (not one) to scroll an overflowed region, which can be tricky.

68 Have you ever come across CSS expressions? They were Microsoft’s proprietary method of inserting DOM scripts into CSS. Don’t bother with them now; they’re totally deprecated.

69 While the CSS cursor property can be useful in certain circumstances, don’t manipulate it in such a way as to make finding the cursor on the screen more difficult.

70 Horizontal scrolling might seem like a unique way to position and style content, but most people aren’t used to it. Decide carefully when such conventions should be used.

71 Until Internet Explorer 9 is final, CSS3 will have some critical compatibility issues. Don’t rely too heavily on it for stable layouts. Use progressive enhancement concepts.

72 CSS makes it possible to provide information on demand. If you can give people information in small chunks, they’ll be more likely to read it.

73 When showcasing a menu in CSS, be consistent in implementation. People want to know about the relationship between objects, and it’s important to avoid dissonance.

74 CSS isn’t a solution to all of your layout woes–it’s a tool to aid your visual journey. Whatever you produce should be usable and logically designed for users (not search engines).

75 Once your layout is marked up with CSS, get feedback on how usable it really is; ask friends, family, co-workers, visitors or strangers for their opinions.

Typography and Color

If one thing deserves its own set of tips, it’s the complex matter of adding typography, color and imagery to CSS. We want readable content and we want it in a consistent layout. In this section, we’ll learn to take advantage of typography and color, which are powerful conventions in design. I’ll talk about "web-safe" and share tips relating to the latest craze of embedding fonts.

Typography and Color"Web-safe" concepts have changed over time and could soon become a non-issue.

76 Squeezing content too close together can decrease overall readability. Use the line-height property to space lines of text appropriately.

77 Be cautious about letter-spacing: too much space and words will become illegible, too little and the letters will overlap.

78 Unless you have good reason, don’t uppercase (i.e. text-transform:uppercase; ) long passages of text (e.g. HEY GUYS AND GALS WHAT’S UP?). People hate reading what comes off as shouting.

79 Accessible websites have good contrasting colors. Tools exist to measure foreground colors against background colors and give you a contrast ratio. Check out this list of tools for checking your design’s colors. Be sure your text is legible.

80 Remember that default styles might differ greatly from browser to browser. If you want stylistic flourish, reinforce the behavior in the stylesheet.

81 In the old days, the number of colors that a screen could display was rather limited. Some people still use old monitors, but the need for web-safe colors has drastically reduced.

82 Building a font stack is essential when making a design degrade gracefully. Make sure that fallback typefaces exist in case the one you request isn’t available.

83 With Vista, Windows 7 and MS Office 07–10 (and their free viewers), a number of cool new web-safe fonts have become available, such as Candara, Calibri and Constantina. Read about Windows fonts.

84 Plenty of smartphone apps can boost your ability to build a stylesheet, but Typefaces for the iPhone and other iOS4 devices is particularly useful because it shows you every font installed.

85 Web-safe fonts are no guarantee; people could quite possibly uninstall a font even as ubiquitous as Arial (or Comic Sans!). Then their browsers wouldn’t be able to render it.

86 Avoid underlining content with the text-decoration property unless it’s a real link. People associate underlined text with hyperlinks, and an underlined word could give the impression that a link is broken.

87 Avoid the temptation to use symbolic typefaces like Wingdings or Webdings in the layout. It might save KBs on imagery, but it’ll serve nonsensical letters to screen-reader users.

88 Remember that @font-face has different file format requirements depending on which browser the user is on, such as EOT, WOFF, TTF and OTF (as you would find on a PC). Serve the appropriate format to each browser.

89 The outline property is seriously underused as an aid to web accessibility. Rather than leaving it set to the default value, use border styles to enhance an active event’s visibility.

90 Smartphones do not have the same level of core support for web typography that desktop browsers do, which means fewer web-safe fonts and no conventional @font-face embedding.

91 Cross-browser opacity that degrades gracefully can be applied using the -ms-, -moz-, -khtml- vendor prefixes and the filter: alpha(opacity=75); property for Internet Explorer.

92 You can make background-image bullets by using list-style-type:none;, adding a padding-left indent and positioning the background-image to the left (with the required pixel offset).

93 Helping users identify an input box is easy; just add a background image of the name (like "Search" or "Password") and set it so that the image disappears when the box is clicked on by using the :focus pseudo-class and then setting the background property to none.

94 Large and visible click regions enhance the usefulness and usability of anchor links, which in turn guide people among pages. Be attentive when you style these.

95 Remember that background images do not replace textual content. If a negative indent is applied, for example, and images are disabled, then the title will be invisible.

96 Navigation items need to be labeled appropriately. If you use a call-to-action button or an image-based toolbar, make sure a textual description is available for screen readers.

97 If the idea of applying opacity with a bunch of proprietary elements doesn’t appeal to you, try RGBA transparency (in CSS3) instead of background-color: rgba(0,0,0,0.5);.

98 If your visitors use IE6, avoid using px as the unit of measurement for text. IE6 users have no zoom functionality; they rely on text resizing, which doesn’t work with px. Use a relative unit instead, such as em.

99 Providing alternative stylesheets for supported browsers such as Firefox and Opera can enhance readability, as in the case of high-contrast alternatives.

100 If you find choosing colors difficult, web-based tools like Adobe Kuler, desktop tools like ColorSchemer Studio and mobile apps like Palettes Pro might help.

Style Can Be Stylish!

CSS has come a long way in recent years. With browser makers implementing the CSS3 specification even before it’s finalized, adding unique proprietary styles (such as WebKit transformations) to the mix and increasingly supporting web standards, there has never been a better time to be a web designer. In the past, we could only hope that our styles would be correctly applied, but it seems that desktop and mobile platforms are improving like never before.

Style Can Be Stylish!Web designs have come a long way since the ’90s, and that’s a good thing.

Implementing CSS can be frustrating, what with ongoing web-browser issues, but it’s still one of the most fun web languages you can engage with. Rather than laying out the structure of objects or fiddling with complex mechanisms, you can dictate how content should appear. It’s like being given a blank piece of paper and a pack of crayons. And designers are experimenting with the available styles to create beautiful experiences for audiences.

Consider the implications of every property and style you declare. CSS can turn the simplest or most minimalist layout into a complex structure of interactivity that would terrify all but the most dedicated individuals. As the capabilities and options in CSS grow and devices are updated to support them, a new wave of unique layouts will appear. Hopefully a number of them will be yours.

Related Content

Alexander Dawson is a freelance web designer, author and recreational software developer specializing in web standards, accessibility and UX design. As well as running a business called HiTechy and writing, he spends time on Twitter, SitePoint’s forums and other places, helping those in need.

 
 

The History of CSS Resets

02 Dec

The History of CSS Resets

When artists begin a new painting, they don’t immediately reach for the cadmium red and the phthalo blue. They first prime the canvas. Why? To ensure that the canvas is smooth and has a uniform white hue.

Many web designers prefer to use a CSS "reset" to "prime" the browser canvas and ensure that their design displays as uniformly as possible across the various browsers and systems their site visitors may use.

This is a three-part series of articles on the topic of CSS resets.

  • Part 1: The History of CSS Reset
  • Part 2: A Guide to CSS Resets (coming soon)
  • Part 3: Should You Use CSS Reset? (coming soon)

What Is CSS Reset?

When you use a CSS "reset," you’re actually overriding the basic stylesheet each individual browser uses to style a web page. If you present a website with no CSS whatsoever, the site will still be styled, to a very limited extent, by the browser’s default stylesheet.

The problem is that every browser’s stylesheet has subtle but fundamental differences. By using a CSS reset, you’re setting the styles of the fundamental CSS elements to a baseline value, thusly rendering the browsers’ varying style defaults moot.

Some of the most common elements that are styled differently among different browsers are hyperlinks (<a>), images (<img>), headings (<h1> through <h6>), and the margins and padding given to various elements.

What Is CSS Reset?

So which browser is right, Firefox or IE? It doesn’t matter. What does matter is that the spacing in between your paragraphs and other elements will look dissimilar if you don’t set a style for a paragraph’s margin and padding. — Jacob Gube, Founder of Six Revisions

It might be useful to peruse this chart showing the various browser defaults. Unfortunately, it doesn’t go back to IE6 (which causes so much havoc among stylesheets).

Who Uses Resets?

According to a 2008 poll by Chris Coyier of CSS-Tricks, a solid majority of web designers use one variation or another of a reset. (Coyier’s parameters were fairly broad, possibly accounting for the heavy support of resets in his poll results.)

The poll, which did not purport to be particularly scientific or comprehensive, gave the following results:

  • 27% use some version of Eric Meyer’s reset
  • 26% indicated they didn’t know what a reset was
  • 15% use a "hard reset," or some iteration of a reset using the universal selector
  • 14% use a reset as part of a larger CSS framework
  • 13% use their own custom reset
  • 4% "purposefully do not use one"

Coyier was not surprised with Meyer’s reset coming in first in the polling, calling it "popular, thoughtful, and effective." Somewhat whimsically perhaps, Meyer replied in the comments: "Huh. I actually didn’t expect that at all; I figured the framework resets would win by a country mile. Now the pressure’s totally on! Arrrrgh!"

Early Days of CSS Reset

As far as I can tell, the first mentions of anything we would later consider to be a "reset" came in late 2004, with two very different approaches.

undohtml.css

The first was legendary developer Tantek Çelik’s UndoHTML.css stylesheet, which "strips the browser varnish" from a number of elements.

/* undohtml.css */
/* (CC) 2004 Tantek Celik. Some Rights Reserved.             */
/*   http://creativecommons.org/licenses/by/2.0                   */
/* This style sheet is licensed under a Creative Commons License. */

/* Purpose: undo some of the default styling of common (X)HTML browsers */

/* link underlines tend to make hypertext less readable,
   because underlines obscure the shapes of the lower halves of words */
:link,:visited { text-decoration:none }

/* no list-markers by default, since lists are used more often for semantics */
ul,ol { list-style:none }

/* avoid browser default inconsistent heading font-sizes */
/* and pre/code too */
h1,h2,h3,h4,h5,h6,pre,code { font-size:1em; }

/* remove the inconsistent (among browsers) default ul,ol padding or margin  */
/* the default spacing on headings does not match nor align with
   normal interline spacing at all, so let's get rid of it. */
/* zero out the spacing around pre, form, body, html, p, blockquote as well */
/* form elements are oddly inconsistent, and not quite CSS emulatable. */
/*  nonetheless strip their margin and padding as well */
ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,body,html,p,blockquote,fieldset,input
{ margin:0; padding:0 }

/* whoever thought blue linked image borders were a good idea? */
a img,:link img,:visited img { border:none }

/* de-italicize address */
address { font-style:normal }

/* more varnish stripping as necessary... */

In an October 2010 email to me, Çelik confirmed he was most likely first out of the gate. "I’m pretty sure I invented/proposed/shared the concept of resetting CSS (though not by that name) in my blog post of 2004," Çelik said.

Çelik’s reset removes link underlines, borders from linked images, and sets the font size to 1em for headings, <code>, and paragraphs. In 2009, author and designer Jason Cranford Teague described Çelik’s reset as "part sublime and part madness," for reasons that elude me.

"hard reset"

The second was web designer and developer Andrew Krespanis’s "hard reset" to overcome browser defaults for margins and padding (in a snippet he called "the tiny addition I threw in at the last minute").

* {
    padding:0;
    margin:0;
}

When asked about the hard reset, Krespanis mused: "That single line of CSS kick-started my career in a big way, which in retrospect is amusing verging on absurd."

"Certainly no one suggested the reset idea to me, it was something I first suggested to CSS beginners on codingforums.com in early 2004 who defended their over-use of superfluous divs by the confusing rendering caused by default margins and padding on paragraphs, blockquotes, lists, fieldsets, etc." Krespanis said. "I also used it whenever providing examples to people, but wasn’t using it for sites until I started suggesting beginners do so. Eric Meyer was talking about a similar concept at the time, only his was more focused on quality sensible defaults to override those set by [browser] makers and he has continued to develop his over the years since."

Really Undoing html.css

Çelik’s reset quickly drew the attention of CSS guru Eric Meyer, who used Çelik’s work as a jumping-off point for his first attempt at a global reset, as well as a follow-up almost immediately thereafter. In the same conversation I had, Çelik said, "About a week and a half later, Eric Meyer went into a lot more detail on his blog and expanded on my work."

The Differences

Perhaps because Krespanis’s method was so simple and so basic (only addressing margins and padding, as opposed to Çelik’s and Meyer’s far more thorough reset), it seemed to attract more attention off the bat. However, this is a simplistic observation. Judging from the comments in both Meyer’s and Krespanis’s blogs, a number of people were considering something along these lines at around the same time; it’s also worth noting that several commenters in Meyer’s blog discussed the margin/padding reset weeks before Krespanis posted about it (Krespanis himself noted the technique on Meyer’s blog before posting on his own).

As the man said, it steamboats when it’s steamboat time. The idea of some sort of CSS reset had become, at least for many designers, a necessary one.

In 2004, Krespanis wrote:

"A big part of dealing with cross-browser differences is accounting for the default property values of elements in each browser; namely padding and margin. I use the following declaration in every new site I design; it has saved me many hours of nitpicking.

* {padding:0; margin:0;}

It doesn’t seem like much at first, but wait till you look at your mildly styled form in 11 browsers to find the positioning identical in all of them; or your button-style lists are perfect the first time, every time.

The difference between Çelik’s and Meyer’s early efforts, and Krespanis’s "afterthought," is, of course, Krespanis’s use of the * (which in CSS, is the universal selector that matches all elements in a web page).

Moving Away from the Universal Selector "hard reset"

Like a drop of antimatter, that single * had widespread effects. As Krespanis went on to note, the use of the universal selector canceled the padding and margin of every element in the page, sometimes to the detriment of the individual design, and it often fouled up forms and lists.

Today, it’s recognized that using the universal selector has repercussions on web page performance because of the resource tax involved in selecting and assigning styles to all elements. Co-creator of the Firefox browser, David Hyatt, advises developers to make sure "a rule doesn’t end up in the universal category," as a best practice for writing efficient CSS.

Russ Weakley, CSS book author and co-chair of the Web Standards Group, outlines a downfall of the "hard reset" method: "Once you have removed all margin and padding, this method relies on you specifically styling the margins and padding of each HTML element that you intend to use."

It didn’t take long for people to start modifying the original "hard reset" to something more specific. Steve Rider, for example, posted what he called a "no assumptions" reset on Meyer’s blog, tweaked to his own preferences:

body {margin: 0px; padding: 8px;}
body, div, ul, li, td, h1, h2, h3, h4, h5, h6 {font-size: 100%; font-family: Arial, Helvetica, sans-serif;}
div, span, img, form, h1, h2, h3, h4, h5, h6 {margin: 0px; padding: 0px;
background-color: transparent;}

Web developer Seth Thomas Rasmussen tossed his hat in the ring, where he gives some padding and margins back to selected elements:

h1, h2, h3, h4, h5, h6, ul, ol, dl, table, form, etc. {margin: 0 0 1em 0}

And it didn’t take long for Krespanis to come up with his own modification:

* {padding:0; margin:0;}
h1, h2, h3, h4, h5, h6, p, pre, blockquote, label, ul, ol, dl, fieldset, address { margin:1em 5%; }
li, dd { margin-left:5%; }
fieldset { padding: .5em; }

Between the wide-ranging resets from Çelik and Krespanis, the more "targeted" resets, and the objections to the sometimes-overwhelming changes the resets made, the games were on. Before long, people were trying all kinds of different resets and posting about it.

Lost and Found: Faruk Ateş and initial.css

In July 2005, Web developer Faruk Ateş posted his initial.css on the now-defunct Kurafire.net. In subsequent discussions on Meyer’s and other design blogs, a few commenters recalled Ateş’s efforts. Through the magic of the Wayback Machine, his initial.css reset can be examined. Like others, Ateş revised his reset after discussion and commentary was received.

Ateş said he had been using his reset for a year or so in his client designs, with little or no ill effect. I believe that his was the first truly "global reset" to become publicly available, though he said in a 2010 email to me that he wasn’t at all sure that was the case. In that same exchange, Ateş wrote: "It was also deliberately kept pretty small, because I didn’t like the idea of a huge ton of CSS to reset everything in the browser, when most every site I was building at the time didn’t actually use 50-60% of the less-common elements that were being reset. … [W]here Eric did the more usable-under-any-circumstances version, exhaustive and very complete (for its time), mine was more of the ‘hey, just these handful of styles have made my life as web developer easier’ and I shared them because, well, why wouldn’t I?"

/* =INITIAL
   v2.1, by Faruk Ates - www.kurafire.net
   Addendum by Robert Nyman - www.robertnyman.com */

/* Neutralize styling:
   Elements we want to clean out entirely: */
html, body, form, fieldset {
        margin: 0;
        padding: 0;
        font: 100%/120% Verdana, Arial, Helvetica, sans-serif;
}

/* Neutralize styling:
   Elements with a vertical margin: */
h1, h2, h3, h4, h5, h6, p, pre,
blockquote, ul, ol, dl, address {
        margin: 1em 0;
        padding: 0;
}

/* Apply left margin:
   Only to the few elements that need it: */
li, dd, blockquote {
        margin-left: 1em;
}

/* Miscellaneous conveniences: */
form label {
        cursor: pointer;
}
fieldset {
        border: none;
}
input, select, textarea {
        font-size: 100%;
}

His reset included:

  • Setting the html, body, form, fieldset elements to have zero margins and padding, and their fonts to 100%/120% and a Verdana-based sans-serif font stack
  • Setting the h1, h2, h3, h4, h5, h6, p, pre, blockquote, ul, ol, dl, address elements to have a 1em vertical margin, no horizontal margin, and no padding
  • Giving a 1em left margin to the li, dd, blockquote elements
  • Setting the form label cursor to pointer
  • Setting the fieldset border to none
  • Setting the input, select, textarea font sizes to 100%

As others noted before, and Meyer noted afterward, Ateş eschewed the universal selector because of its detrimental effect on forms (though it was in his first iteration).

For whatever reason, Ateş’s reset received a good bit less attention than some of the others, though it’s clear that many elements in the YUI and Meyer resets that followed appeared first in Ateş’s coding.

In October 2010, Ateş wrote that he never rewrote his reset after the single revision: "Any additions I would have made to it would’ve made it quickly grow in size, at which point people could’ve and should’ve just used Eric’s more comprehensive one. Eventually I stopped using my own initial.css and nowadays I usually copy from YUI or, more recently, the HTML5 Boilerplate, which contains parts from both YUI and Eric Meyer’s latest reset." In 2007, Web designer Christian Montoya provided an updated version of Ateş’s reset that he relies on for his own work.

The Yahoo! User Interface CSS Reset

The Yahoo! User Interface (YUI) reset first came on the scene in February 2006, written by Nate Koechley, the YUI senior frontend engineer, along with his colleague Matt Sweeney.

body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td {
	margin:0;
	padding:0;
}
table {
	border-collapse:collapse;
	border-spacing:0;
}
fieldset,img {
	border:0;
}
address,caption,cite,code,dfn,em,strong,th,var {
	font-style:normal;
	font-weight:normal;
}
ol,ul {
	list-style:none;
}
caption,th {
	text-align:left;
}
h1,h2,h3,h4,h5,h6 {
	font-size:100%;
	font-weight:normal;
}
q:before,q:after {
	content:'';
}
abbr,acronym {
  border:0;
}

The effects of this reset on any stylesheet were dramatic. While the html element was left untouched, almost every often-used HTML element had its margins and padding zeroed out. Images lost their borders. Lists lost their bullets and numbering. And every single heading was reset to the same size.

The reset was, of course, one part of a much larger framework, called the Yahoo! User Interface Library (YUI), which is a framework for developing web-based user interfaces.

The first YUI CSS Reset was, I believe, the first truly "global" CSS reset that received widespread public notice. Microsoft Developer Network blogger, Dave Ward said, "YUI’s reset is the first that could truly be considered a CSS reset by current standards."

The idea, as Koechley said in multiple presentations and blog posts, was to provide a "clean and sturdy foundation" for an identically formatted "clean slate" that individual stylesheets can build upon for a nearly-identical look no matter what browser or machine is being used to display the site. The YUI CSS Reset "removes everything" stated by the browser’s default CSS presentation.

In a September 2006 presentation given at Yahoo’s "Hack Day" event, Koechley told the audience: "Sound foundation ensures sane development." The reset "overcome[s] browser.css" and "level[s] the playing field."

In a bit of whimsy, Koechley wrote that the YUI CSS Reset "[h]elps ensure all style is declared intentionally. You choose how you want to <em>phasize something. Allows us to choose elements based on their semantic meaning instead of their ‘default’ presentation. You choose how you want to render <li>sts."

In an October 2007 slideshow, Koechley reminded users that the reset is "a good reminder that HTML should be chosen based on content alone." He restated that in a 2010 interview and went on to note that most people still don’t know that the browsers provide a strong layer of presentational functionality. If nothing else, he said, resets serve to bring all browsers down to a "neutralized, normalized … lowest common denominator" state that designers can then build from. Resets, he said, force people to rethink the semantics of HTML elements.

Koechley no longer works for the YUI team, and is instead a freelance web developer. He isn’t sure what, if any, changes will be made in the YUI reset to accommodate HTML5 and CSS3.

Eric Meyer used the YUI reset as a base for his own expansive reset, garnering even more attention than the YUI code.

Eric Meyer’s CSS Reset

Why do this at all? The basic reason is that all browsers have presentation defaults, but no browsers have the same defaults. … We think of our CSS as modifying the default look of a document — but with a ‘reset’ style sheet, we can make that default look more consistent across browsers, and thus spend less time fighting with browser defaults. — Eric Meyer, Author of leading CSS books

To paraphrase the 1983 commercial, when Eric Meyer talks, people in the design and development community listen. He started with a September 2004 post that, as noted above, itself built on work by Tantek Çelik.

Both Meyer and Çelik focused on "undoing" the html.css file that controlled the way Gecko-based browsers like Firefox and SeaMonkey displayed websites on the individual computer. Meyer’s follow-up on the first post focused on (fractionally) rebuilding the html.css file to make sites relatively usable again.

Both Çelik and Meyer envisioned their work as immediately practical and applicable to web design. Çelik told me that his reset "just made sense as a foundation to simplify coding CSS and make it more predictable" — and it didn’t take them, nor anyone else, apparently, very long to begin to comprehend how they could gain new control over the display across almost all browsers. The power, the power!

Meyer had other fish to fry in the ensuing years, including the birth of a daughter, the care and feeding of a radio show featuring big band and jazz music, and a truly intimidating schedule of design projects and conferences. However, he returned to the subject of CSS resets in April 2007. He brought up the topic at the 2007 An Event Apart conference in Boston, where he specifically avoided the idea of using a universal selector to reset the CSS. "Instead," he wrote, "I said the styles should list all the actual elements to be reset and exactly how they should be reset."

Meyer based his "blanket reset" on Yahoo’s YUI reset, making some significant tweaks along the way. Meyer’s reset.css code included the following:

Eric Meyer’s CSS Reset (2007)

html,body,div,span,
applet,object,iframe,
h1,h2,h3,h4,h5,h6,p,blockquote,pre,
a,abbr,acronym,address,big,cite,code,
del,dfn,em,font,img,ins,kbd,q,s,samp,
small,strike,strong,sub,sup,tt,var,
dd,dl,dt,li,ol,ul,
fieldset,form,label,legend,
table,caption,tbody,tfoot,thead,tr,th,td {
	margin: 0;
	padding: 0;
	border: 0;
	font-weight: normal;
	font-style: normal;
	font-size: 100%;
	line-height: 1;
	font-family: inherit;
	text-align: left;
}
table {
	border-collapse: collapse;
	border-spacing: 0;
}
ol,ul {
	list-style: none;
}
q:before,q:after,
blockquote:before,blockquote:after {
	content: "";
}

Two things to note with regards to the 2007 version:

  • The biggest selector, which includes more HTML elements such as <applet>, also sets other CSS properties such as line-height and text-align
  • Some elements, such as <hr>, <input>, and <select> were left out of the CSS reset

Meyer intentionally avoided the universal selector to preserve resetting "inputs and other interactive form elements." He continued: "If the :not() selector were universally supported, I’d use it in conjunction with a universal selector, but it isn’t."

Eric Meyer’s reset took the concept of resetting margin and padding and took it to a whole new level, stripping styles from a number of elements, forcing you to think about what you wanted and add them back in. List items would no longer have bullets, headings would no longer be bolded, and most elements would be stripped of their margin and padding, along with some other changes. — Jonathan Snook, Author, Front-End Developer

The effects of both the YUI reset and the Meyer reset were staggering. Almost everything included in the browser’s default stylesheet was reset to zero, including many elements designers rarely touched. Interestingly, the first comments on Meyer’s reset suggested more additions to the reset, particularly to removing link borders and setting the vertical-align property to baseline. For example, Jens O. Meiert, a web designer/developer who works at Google commented: "Is that a trick style sheet? Why should anyone interested in elegant code style use such a style sheet, that even in multi-client projects results in way too many overridden properties?"

Others complained about the redundancy of resetting elements to zero and then re-resetting them later in the stylesheet, adding unwanted weight to the stylesheet. Of course, others defended the reset, resulting in a lively (yet polite and mutually respectful) debate.

The fracture lines in the development/design community over the idea of the "global reset" were already beginning to appear. (More about that is forthcoming.)

Meyer made some significant changes to his original reset; two days later, he added a comment about background colors, changing the font-weight and font-style properties to inherit, resetting the vertical-align attribute to baseline, and zeroing out the borders on linked images.

Eric Meyer’s CSS Reset (2007, revision 1)

/* Don't forget to set a foreground and background color
   on the 'html' or 'body' element! */
html, body, div, span,
applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
dd, dl, dt, li, ol, ul,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
	margin: 0;
	padding: 0;
	border: 0;
	font-weight: inherit;
	font-style: inherit;
	font-size: 100%;
	line-height: 1;
	font-family: inherit;
	text-align: left;
	vertical-align: baseline;
}
a img, :link img, :visited img {
	border: 0;
}
table {
	border-collapse: collapse;
	border-spacing: 0;
}
ol, ul {
	list-style: none;
}
q:before, q:after,
blockquote:before, blockquote:after {
	content: "";
}

And two weeks after that, he tweaked the code yet again. This time adding minor chances such as the background: transparent property declaration to the first rule and removing the outline on the :focus pseudo-class.

Eric Meyer’s CSS Reset (2007, revision 2)

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
	margin: 0;
	padding: 0;
	border: 0;
	outline: 0;
	font-weight: inherit;
	font-style: inherit;
	font-size: 100%;
	font-family: inherit;
	vertical-align: baseline;
}
/* remember to define focus styles! */
:focus {
	outline: 0;
}
body {
	line-height: 1;
	color: black;
	background: white;
}
ol, ul {
	list-style: none;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
	border-collapse: separate;
	border-spacing: 0;
}
caption, th, td {
	text-align: left;
	font-weight: normal;
}
blockquote:before, blockquote:after,
q:before, q:after {
	content: "";
}
blockquote, q {
	quotes: "" "";
}

After some more cogitation and discussion, he released another version of his reset. He changed the way quotes are suppressed in the blockquote and q elements, and removed the inherit values for font-weight and font-style.

Eric Meyer’s CSS Reset (2008)

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
	margin: 0;
	padding: 0;
	border: 0;
	outline: 0;
	font-size: 100%;
	vertical-align: baseline;
	background: transparent;
}
body {
	line-height: 1;
}
ol, ul {
	list-style: none;
}
blockquote, q {
	quotes: none;
}

/* remember to define focus styles! */
:focus {
	outline: 0;
}

/* remember to highlight inserts somehow! */
ins {
	text-decoration: none;
}
del {
	text-decoration: line-through;
}

/* tables still need 'cellspacing="0"' in the markup */
table {
	border-collapse: collapse;
	border-spacing: 0;
}

And finally, he released an ever-so-slightly modified version of the reset as what seems to be the final iteration, warning users: "I don’t particularly recommend that you just use this in its unaltered state in your own projects. It should be tweaked, edited, extended, and otherwise tuned to match your specific reset baseline. Fill in your preferred colors for the page, links, and so on. In other words, this is a starting point, not a self-contained black box of no-touchiness."

Eric Meyer’s CSS Reset (most current)

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
	margin: 0;
	padding: 0;
	border: 0;
	outline: 0;
	font-size: 100%;
	vertical-align: baseline;
	background: transparent;
}
body {
	line-height: 1;
}
ol, ul {
	list-style: none;
}
blockquote, q {
	quotes: none;
}

/* remember to define focus styles! */
:focus {
	outline: 0;
}

/* remember to highlight inserts somehow! */
ins {
	text-decoration: none;
}
del {
	text-decoration: line-through;
}

/* tables still need 'cellspacing="0"' in the markup */
table {
	border-collapse: collapse;
	border-spacing: 0;
}

And it wasn’t long before designers found problems in the "final" version of the reset. So nothing is ever really final.

The evolution of Meyer’s thinking, as it was affected by his own reflection and the input from many others is fascinating. Meyer has frequently reminded designers that they shouldn’t just slap his reset stylesheet into their work willy-nilly.

In the 2008 An Event Apart conference in Chicago, Meyer, according to participant Trevor Davis, told designers not to "just drop in his reset stylesheet if there is a more effective way to accomplish the same thing." He said, "Instead, turn the reset into a baseline. Modify the reset stylesheet to suit your project, don’t use his reset stylesheet without modifying anything. Don’t reset then re-style, reboot instead."

In a 2010 interview, Meyer told me: "I had not anticipated it being, you know, popular. I hadn’t really anticipated tons of people using it. I had sort of anticipated, ‘Hey, here’s a way of thinking about this, you know, here’s what people who really have a lot of experience with this might take as a starting point and play with it, and like, we’re all sort of professionals here and we get what this is about.’ And it kind of went everywhere and got used by tons of people who maybe haven’t thought about the Web for a decade or more as some of us have. … You have to be careful about what you throw out there in the world because you never know what’s going to catch on."

Conclusion

This in-depth inspection of the history of CSS resets should set the stage for what we will talk about next in this three-part series of articles. In part 2, we will discuss the various CSS reset options available to you for incorporation into your projects. In part 3, we will discuss the on-going debate on whether or not web designers should use CSS resets.

This is a three-part series of articles on the topic of CSS resets.

  • Part 1: The History of CSS Reset
  • Part 2: A Guide to CSS Resets (coming soon)
  • Part 3: Should You Use CSS Reset? (coming soon)

Related Content

About the Author

Michael Tuck is an educator, writer, and freelance web designer. He serves as an advisor to the Web Design forum on SitePoint. When he isn’t teaching or designing sites, he is doing research for the History Commons. You can contact him through his website, Black Max Web Design.

 
 

10 Random CSS Tricks You Might Want to Know About

22 Oct

10 Random CSS Tricks You Might Want to Know About

CSS is the fundamental way of styling our web pages. Its deceptively easy syntax allows us to do many things to affect the visual layer of our work. And especially with CSS3, the language has gotten even more powerful.

There are many useful CSS techniques and tricks out there for you to take advantage of. This is a collection of a few useful CSS snippets that you might want to keep in your toolkit.

1. Set body font-size to 62.5% for Easier em Conversion

If you would like to use relative units (em) for your font sizes, declaring 62.5% for the font-size property of the body will make it easier to convert px to em. By doing it this way, converting to em is a matter of dividing the px value by 10 (e.g. 24px = 2.4em).

body {
  font-size: 62.5%; /* font-size 1em = 10px */
}
p {
  font-size: 1.2em; /* 1.2em = 12px */
}

2. Remove outline for WebKit Browsers

When you focus (:focus) on an input element, perhaps you have noticed that Safari adds a blue border around it (and Chrome, a yellow one).

Remove outline for WebKit Browsers

If you would like to remove this border outline, you can use the following style rule (this removes the outline from text fields):

input[type="text"]:focus {
  outline: none;
}

Please note that outline is used for accessibility purposes so that it is easier to see what input field is active. This is beneficial for those with motor impairments who cannot use a point-and-click device (such as a mouse), and thus must rely on alternative means of navigating a web page, such as the Tab key. The outline is also useful for able-bodied users who use keyboard shortcuts to get to web form input fields (it’s easier for them to see which input is currently active). Therefore, rather than completely taking out the outline, consider styling your input fields such that it indicates that it is the focused element.

3. Use CSS transform for Interesting Hover Effects

For progressive enhancement, you could use the transform property that is supported by many browsers that have CSS3 support.

Here’s a trick for enlarging a elements on hover by 110%.

a {
  -moz-transform: scale(1.1);
  -webkit-transform: scale(1.1);
  -o-transform: scale(1.1);
}

Use CSS transform for Interesting Hover Effects

4. Target IE6 and IE7 Browsers without Conditional Comments

Need to target IE browsers? Here is a quick hack that doesn’t require conditional comments (note that your CSS will therefore not pass auto-validation, which is fine if you are aware of why it doesn’t).

The code below will change the background-color of divs depending on what browser the user is viewing the web page under. Since * cascades down to IE7 and below, we use _ after that declaration so that IE6 (and below) has a different background color from IE7.

div {
  background-color: #999; /* all browsers */
  *background-color: #ccc; /* add a * before the property - IE7 and below */
  _background-color: #000; /* add a _ before the property - IE6 and below */
}

5. Support Transparency/Opacity in All Major Browsers

This example gives the div element a 70% opacity. We need to use proprietary CSS to get it to work on Internet Explorer (which will invalidate our code under W3C standards).

div {
/* standards-compliant browsers */
opacity:0.7;

/* The following is ignored by standards-based browsers */
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=70)";  /* IE8 */
filter: alpha(opacity=70); /* IE 5-7  */
}

6. Use !important to Override Normal CSS Precedence Rules

In CSS, when two properties apply to the same element, the one that is farther down the stylesheet is the one that will take effect. However, by using !important at the end of a property value, this can be changed.

Let’s take, for example, this set of style rules:

h1 { color: green; }
h1 { color: red; }

The h1 element will have a red color with the CSS above.

If we wanted to change the style rule’s priority without changing the order of the property declaration, then we simply do the following:

h1 { color: green !important; }
h1 { color: red; }

Now, the <h1> element will be green.

7. Centering a Fixed-Sized Element

Here is one way to center a fixed-width/fixed-height div at the center of its container. This could be adapted to centering text, images, etc. within their containers. Essentially, we do a bit of arithmetic to get the fixed-sized element centered using absolute positioning and margins. Note that the parent container must have a position: relative property for this to work.

div {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 400px;
  height: 300px;
  margin-top: -150px; /* 1/2 of your element height*/
  margin-left: -200px; /* 1/2 of your element width */
}

Centering a Fixed-Sized Element

8. Easy Web Fonts with Google Font API

Web fonts allow you to step outside of the normal web-safe fonts by taking advantage of CSS’s @font-face rule. However, right now, browsers aren’t uniform in its implementation of @font-face. More specifically, web browsers differ in the types of font files they support (hopefully this will change with the WOFF standards). Additionally, you must be careful with the fonts you use since some of them might not be licensed for web use.

To sidestep the issues with @font-face, the Google Font API is here to the rescue.

Here is an example of using the Cantarell font on <h1> elements that takes advantage of Google Fonts API.

If you want to use the Cantarell font from Google Font API, first reference the remote stylesheet inside your <head> tags as such:

<link href="http://fonts.googleapis.com/css?family=Cantarell" rel="stylesheet" type="text/css">

To use the font in h1 elements, simply use the font-family CSS property.

h1 {
  font-family: 'Cantarell', Arial, serif;  /* Use a font stack, just in case. */
}

9. Prevent Line-Wrapping of Text Elements

Sometimes, you don’t want your text to wrap to the next line if it happens to reach the end of the width of its containing element.

Here is how a normal anchor text works when it reaches the end of its parent element’s width:

Notice that the link wraps at a whitespace in the text. What if we always want our links to be on the same line all the time (i.e. to prevent wrapping)? Simple. We just use the white-space property.

a { white-space: nowrap; }

Now, our links won’t wrap.

10. Vertically Align Text

We can use a variety of methods for horizontally aligning text (such as text-align: center or margin: 0 auto) but it’s slightly trickier to vertically align text.

However, for single-line text, we can use the line-height property. By setting the line-height property of the text element to the same height of its container, it will become vertically centered.

Here is a p element that is horizontally-centered inside a 100×100px div using text-align: center:

Vertically Align Text

As you can see, text-align doesn’t center it vertically. To fix that, we can set line-height to the same height as the containing div (100px).

div { width:100px; height:100px; }
div p { line-height:100px; }

Vertically Align Text

Note that this assumes the p element has no margin or padding. If you have margin or padding at the top or bottom of the p element, you need to compensate for them accordingly or just simply set padding and margin to 0 to make life easier.

Also, this trick becomes troublesome when there is more than one line of text (i.e. when the text wraps) because there will be a space between the text lines that is equivalent to the line-height value.

It’s your turn to share. Share your own favorite CSS tricks and techniques in the comments.

Related Content

About the Author

Catalin Rosu, a.k.a. Red, is a web designer and developer with over 5 years experience in the industry. You can find articles or tutorials on CSS tips and tricks by visiting his blog at red-team-design.com. You can connect with him on Twitter as @catalinred.

 
 

Useful Collection of Cheat-Sheet Desktop Wallpaper for Web Designers

07 Oct

Typical cheatsheets tend to be over-sized documents, far too large to be viewed in its entirety on a desktop and not too handy for the super-fast reference that is needed. To get the full benefit of any cheatsheat, your only real option is to print it out and keep it close at hand. Wouldn’t it be nice if there was an easier way, a quicker way. Of course there is – what good be handier than having a cheatsheet set as your desktop wallpaper? Always there for quick reference, no need to print it out and no need to scroll through an over-long document.

In this post we have rounded up a selection of cheatsheet wallpapers, in various sizes, covering various technologies, like CSS, HTML5, WordPress, Javascript and many more.

WordPress Help Sheet Wallpaper

WordPress Help Sheet Wallpaper
The WordPress Help Sheet Wallpaper is a simple desktop wallpaper listing Basic Template Files, PHP Snippets for the Header, PHP Snippets for the Templates, Extra Stuff for WordPress, based on the WPCandy WordPress Help Sheet.
Download: 2560x1600px.

Drupal Cheat Sheet Desktop Wallpaper

Drupal Cheat Sheet Desktop Wallpaper
The Drupal Cheat Sheet Desktop Wallpaper is a desktop wallpaper that features the most popular variables of the open source content management system Drupal.
Download: 1024x768px1280x800px1440x900px1680x1050px1920x1200px.

HTML5 Canvas Cheat Sheet

HTML5 Canvas Cheat Sheet
The information on this wallpaper is pretty much just a copy of what is found in the WHATWG specs, just condensed and a little bit easier to read. There are virtually no explanations, and no examples other than some graphics for compositing values. It's basically just a listing of the attributes and methods of the canvas element and the 2d drawing context.
Download: 1388x1027px.

CSS Cheat Sheet Wallpaper in Helvetica

CSS Cheat Sheet Wallpaper in Helvetica
This is the very popular CSS cheat sheet in Helvetica from styl.eti.me. Simplistic in appearance, but very useful for quick referencing. Unfortunately we can not find a working download link for this cool wallpaper, but the good news is they do have a PSD version available. So download it and resize.
Download: CSS Cheat Sheet Wallpaper in Helvetica.

TextMate Shortcuts Wallpaper

TextMate Shortcuts Wallpaper
Here is a TextMate wallpaper that will guide you through some of its powerful features and help you get a handle on all of the keyboard shortcuts. The PSD file is also available.
Download: 1280x800px1920x1200px.

Yahoo! UI (YUI) Cheat Sheets as Wallpaper

Yahoo! UI (YUI) Cheat Sheets as Wallpaper
Yahoo! provides a number of cheat sheets for their YUI library widgets however these are all in PDF format and not usable as wallpaper. However, here you will find all of those cheatsheets converted to PNG images of various sizes all for your desktop.
There are wallpapers available for Animation, Calendar, Connection Manager, Dom Collection, Drag & Drop Event, Utility & Custom Event Logger, Slider and TreeView. And all are available in the following desktop sizes: 1400x1050px, 1280x960px, 1165x900px and 1024x768px.
Download: Yahoo! UI (YUI) Cheat Sheets as Wallpaper.

jQuery 1.3 Cheat Sheet Wallpaper

jQuery 1.3 Cheat Sheet Wallpaper
Download: 1440x900px1680x1050px1920x1200px.

Prototype Dissected Wallpaper

Prototype Dissected Wallpaper
If you need a little help in getting to know Prototype a little better and some help in understanding how the code works, then this is the wallpaper for you. You have a choice of either a dark or white wallpaper, and are available in these sizes: 1280x960px and 1440x900px.
Download: 1280x960px (Dark)1440x900px (Dark)1280x960px (White)1440x900px (White).

Git Cheat Sheet Wallpaper

Git Cheat Sheet Wallpaper
Download: 1100x850px3300x2550px.

A Themer's Cheatsheet Wallpaper

A Themer's Cheatsheet Wallpaper
A Themer's Cheatsheet Wallpaper is a quick refresher of web design fundamentals directly on your desktop. It is available for download in several different colors and the original SVG has been released to the Public Domain.
Download: 1280x800px (Blue)1280x800px (Red)1280x800px (Black)1280x800px (Green).

Font Anatomy Wallpaper

Font Anatomy Wallpaper
Download: 1920x1200px.

SEO Wallpapers

SEO Wallpapers
Think of it as a desk reference checklist that is always at your fingertips. From pre-campaign to reporting, the basics (and more) are right here for you to put directly on your desktop.
Download: 1024x768px1280x960px1280x1024px1440x900px.

Periodic Table of Typefaces

Periodic Table of Typefaces
Download: 1024x768px1280x800px1280x1024px1440x900px1680x1050px1920x1200px.

Color Theory Quick Reference Poster

Color Theory Quick Reference Poster
The Color Theory Quick Reference Poster for Designers has all of the basics of color theory contained in one place – specifically, a cool infographic-esque poster. This way, you can quickly reference things that may have slipped to the back of your mind since design school.
Download: 1280x800px1440x900px1680x1050px1920x1200px.

Web Designer Wallpaper

Web Designer Wallpaper
Download: 1280x1024px (White)1280x1024px (Dark)1680x10050px (Dark)1280x1024px (White).

You might also like…

14 Essential WordPress Development and Design Cheat Sheets »
17 Productive Photoshop Cheatsheets and Reference Cards to Download for Free »
The Best Cheat Sheets for Web Designers and Developers (From CSS, Ajax, Perl, Vbscript…) »
CSS References, Tutorials, Cheat Sheets, Conversion Tables and Short Codes »
20 CSS3 Tutorials and Techniques for Creating Buttons »
50 Useful Tools and Generators for Easy CSS Development »
50 Essential Web Typography Tutorials, Tips, Guides and Best Practices »
The Blueprint CSS Framework – Tutorials, How-to Guides and Tools »

 
 

Change Any Web Page’s Design Instantly with Chrome Extension Stylebot

21 Sep


One of our favorite web browsers just got a cool new tool in the form of Stylebot, a new Chrome extension that allows you to access and modify the CSS for any web page from within the browser.

That’s right — users get a completely customized design experience for any page they choose. The changes they make can be saved for later use and synced across multiple devices.

This is great news for you design enthusiasts as well as for end users with specific needs and wants for their browsing experience. For example, the extension makes web pages with small fonts more accessible by allowing users to increase the font size, and it can make browsing the web less commercial by removing ads.

Stylebot generates a sidebar full of basic and advanced CSS options that allow the end user to manipulate how content is displayed. This tool is simple enough to be used by a moderately competent consumer, but it also has options better suited for those with web design skills. Stylebot can be used to change font attributes, remove advertising, move page elements, change colors, write one’s own CSS selectors and quite a bit more.

Googler Rachel Shearer wrote the following today on the company’s blog:

“For example, a Stylebot user with special reading needs might change a webpage by removing images, picking new text and background colors, and even moving blocks of text around. And Stylebot saves the custom style they create, so the next time they access that page the changes will still be there. Even better, they can sync their saved styles across computers so that webpage will always appear with their preferred style.”

Check out this brief demo video to see Stylebot in action:

Stylebot was created as a Google Summer of Code project by Ankit Ahuja, a computer science student in New Delhi, India. Stylebot is open source and forkable; interested parties can check out Ahuja’s source on GitHub. He said he used elements of other open-source projects, such as Aristo and Firebug, in his work.

What do you think of Stylebot so far? Would you use it to prettify the ugliness that is Craigslist, for example, or to simplify content viewing on a news site?


Reviews: Craigslist

More About: accessibility, chrome, chrome extension, Chromium, CSS, design, designers, Google, google chrome, stylebot, web design

For more Dev & Design coverage:

 
 

10 Interesting CSS3 Experiments and Demos

25 Jul

10 Interesting CSS3 Experiments and Demos

You’ve heard it plenty of times before: We’re at the precipice of a transition in the way we, as developers, do things. Leading the way are future standards like CSS3 and HTML5, both already partially implemented in 4 out of the 5 major web browsers, with IE9 promising support, empowering us with new ways of making interactive and rich user experiences.

Just how awesome is CSS3? Find out by checking out these 10 experiments and demos that push the capabilities of the specs.

1. Our Solar System

Our Solar System

This experiment presents our solar system’s planetary orbits (fast-forwarded, of course) by utilizing CSS3’s border-radius, transform, and animation. Additionally, hovering over the names of each planet on the right displays an animated tooltip using CSS (learn how to make CSS3 animated tooltips). You can read about how this experiment was developed from this walkthrough by Alex Girón, the creator of this stellar CSS3 demonstration. The animation, at the moment, only works on the WebKit browsers (Google Chrome and Safari).

2. CSS3 Ads Versus Flash Ads

CSS3 Ads Versus Flash Ads

Flash animated web banners are notorious for being intrusive in the user’s experience. Ad-blocking apps can turn these off by looking for all embedded Flash objects on a web page and hiding them. However, using CSS3 animation, these Flash ads can be mimicked in functionality, but will be harder to disable with third-party software. In this experiment, several ads were recreated using CSS3, and the results are almost identical to their Flash-constructed counterpart.

3. CSS3-Man

CSS3-Man

This is a robust animation sequence inspired by the Spider-Man animated television series in the 60’s. Making the sequence work involved using CSS3’s transform, @key-frame and rotate; a bit of jQuery was used to preload the images as well as HTML5 for the audio. The creator wrote an explanation of how the CSS3-Man animated sequence works, which will give you a general idea of the level of effort involved in this amazing experiment.

4. The Man From Hollywood

The Man From Hollywood

This demonstration is an animated sequence (based on kinetic typography) that explores a way in which we can replace rich animation components such as Flash or After Effects. This proof of concept chiefly utilizes advanced CSS selectors and CSS3 animation, however, it’s not purely CSS since JavaScript was used to toggle element classes on and off.

5. Anigma

Anigma

We often use Flash (or Silverlight) for rich and interactive web-based video games. This CSS3 demonstration is a puzzle game and a proof-of-concept of how we can use open standards to create games — though admittedly, not as facile as Flash yet if you compare it to Flash games on sites like Kongregate. HTML5’s <audio> element was used to embed the sound.

6. Animated Polaroids

Animated Polaroids

This demonstration is of stacked images that look like Polaroids. Hovering over a photograph transitions it smoothly to the front of the stack, making for an interesting interaction for presenting your photo gallery. The demo was made by leveraging transition, transform, dynamic psuedo-selectors (to animate the target element), as well as stylistic properties such as box-shadow for visual effects. Read the tutorial on how this was constructed if you’d like to learn how this was developed.

7. CSS3 Music Player Menu

CSS3 Music Player Menu

With HTML5’s <audio> and <video> APIs, which will enable us to utilize multimedia without dependence from proprietary plugins, we’ll eventually have a need for GUIs that provide our users with controls for the media we serve them. Though we could use static images in conjunction with other HTML elements (such as buttons) to build these interfaces, using just HTML and CSS to render media controls mean we’ll have a more malleable solution. This user interface for a music player was built using only CSS3 (gradient, border-radius, box-shadow and all that good stuff). Read the explanation on how this was contructed in this tutorial.

8. Sliding Vinyl with CSS3

Sliding Vinyl with CSS3

This demonstration, found in the ZURB Playground, takes vinyl album covers that, when hovered on, animates the sliding out of a vinyl record that contains additional controls ("more information" and "play"). This proof of concept could one day be used as an elegant web-based interface for a site that plays music when combined with HTML5’s  <audio> API.

9. Gabriel Sharp’s Small Planet

Gabriel Sharp's Small Planet

This animated cartoon sequence depicts a fast-forwarded cycle of day and night. It works on WebKit browsers (Safari and Chrome) using the @keyframes CSS3 property for moving and transitioning PNG images.

10. Falling Leaves

Falling Leaves

WebKit presents the capabilities of CSS3’s animate property with a spectacularly smooth demonstration of falling leaves. Tip: Use your browser’s "view source" feature to read the source code of the demonstration — the code’s well documented with explanations of how it works. Read WebKit’s blog post about the animate property to get a better feel for all the possibilities.

Related Content

About the Author

Jacob Gube is the Founder and Chief Editor of Six Revisions. He’s also a web developer/designer who specializes in front-end development (JavaScript, HTML, CSS) and also a book author. If you’d like to connect with him, head on over to the contact page and follow him on Twitter: @sixrevisions.

 
 

Saving Bandwidth and Improving Site Speed Using CSS Sprites

03 Jul

Saving Bandwidth and Improving Site Speed Using CSS Spites

As a site owner, possibly the worst experience that you could serve upon your visitors is a frustrating wait whilst the clock spins and the page loads. In most cases, most of your potential customers would have pressed the back button in their browser and headed off somewhere else; this inevitably means a loss of potential business.

Site speed is predicted to become one of Google’s next ranking factors, although as per normal, the company tends to keep the nitty-gritty close to its chest.

In a presentation in Las Vegas, when pressed on the subject of site speed integration into the Google search ranking algorithm, Matt Cutts, member of the Search Quality group at Google and a highly-regarded person in the SEO community, described this as one of his "what to expect in 2010" bullet points. He went on to explain that the company wanted search to be "real fast, as if you are flipping through a magazine."

What all of this should tell us is that if you wish your site to be user-friendly and well-positioned within the ranks of the major search engines, then you should be looking at ways to improve your web page performance. Apart from the myriad of options displayed in Google Webmaster Tools, including consolidating and compression of external files, and checking for broken links on your website, I would recommend looking at the way you use images. One of the best web design techniques out there is the use of CSS sprites.

What are CSS Sprites?

It may be a common misconception that a sprite implies a series of small images. The opposite, in fact, is the truth — a CSS sprite is one large image.

You may be aware of the CSS technique of displaying an "on/off" state for a button which is contained within a single image and positioned using the background-position CSS attribute on :hover (see the tutorial on a button that uses CSS sprites). CSS sprites are basically the same concept: The image is displayed on the page using the coordinates specified in your CSS, and only this area will be visible.

It is easy to believe that a number of small images are likely to be less heavy in total file size than one containing all of the images positioned together. But even if you may have images that are only a few bytes in size, each one is giving your web server unnecessary work to do by sending an HTTP request. Each request contains a portion of overhead information that uses valuable site bandwidth.

Using CSS sprites can reduce the number HTTP requests and can make the web page seem more responsive because all interface elements are already downloaded before the user handles them. This technique can be very effective for improving site performance, particularly in situations where many small images, such as menu icons, are used.

Building a Basic CSS Image Background Sprite

Let’s discuss this topic using an example. Using Photoshop, I created a document with a series of images (logos of companies) and divided the area into chunks of 100 pixels (see the images below). I saved the file and named it logos.jpg.

I used 100-pixel measurements between logos for the purposes of illustrating the concept in this article and because this was a convenient distance to move the position of the CSS background image each time when manipulating the coordinates in my CSS (you should be more accurate when actually applying CSS sprites to reduce its file size further).

The CSS background image is focused on displaying only the first logo as defined by the green border — the coordinates of which are y = 0 and x = 0.

What are CSS Sprites?

To position them, we use the background-position attribute.

What are CSS Sprites?

To display the second image alongside the first, all that is necessary is to adjust the coordinates on the x-axis.

Because of the way we have constructed the image (at 100-pixel intervals), all we need do is add a line of CSS advancing the x-axis by 100 pixels to display each logo.

CSS for the CSS Background Sprite

#logos {height: 64px; margin: 0; padding: 0; position: relative;}

#logos li {background: url(/logos.jpg) no-repeat top left; margin: 0; padding: 0; list-style: none; position: absolute; top: 0;}

#logos a {height: 64px; display: block;}
// First logo
#logos li a.jaz {background-position: 0 0}
// Second logo
#logos li a.iberotel {background-position: 0 -100px;}
// Third logo
#logos li a.solymar {background-position: 0 -200px;}
// Fourth logo
#logos li a.travcotels {background-position: 0 -300px;}
// Fifth logo
#logos li a.intercity {background-position: 0 -400px;}

The Results of Using CSS Sprites

The Results

In the example above, it was possible to reduce the file size from 52kb to 22kb and the number of HTTP requests from 5 to 1. This represents a good saving, and is only one small section of a web page!

Our new CSS sprite method tests well in most modern browsers. The notable exception is Opera 6 (all Opera versions, not just Opera 6, comprise 1.98% of all web browser usage[1]), which doesn’t apply a background image on link hover states. The links still do work, and if they’ve been labeled properly, the net result will be a static — but usable — image map in Opera 6. This could be an acceptable price to pay, especially now that Opera 7 has been around for a while.

Further Reading on CSS Sprites

Here is a list of suggested reading resources about CSS sprites.

References

  1. Usage share of web browsers (May 2010)

Related Content

About the Author

Peter Richards is a SEO engineer based near Brighton in the UK. He has also spent time as web designer and front-end developer (HTML, CSS, JavaScript). If you wish to connect with him, you can follow Peter on Twitter as @pgrichards.

 
 

Quick Tip: Multiple Borders with Simple CSS

21 Jun

Did you know that we can achieve multiple borders with simple CSS, by using the :after amd :before psuedo-classes? This is something I recently learned myself! I’ll show you how to add more depth to your designs, without images, in just a few minutes.


Final Code

<!DOCTYPE html>

<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Multi-Borders</title>
	<style>
		body { background: #d2d1d0; }

		#box {
			background: #f4f4f4;
			border: 1px solid #bbbbbb;
			width: 200px;
			height: 200px;
			margin: 60px auto;
			position: relative;
		}

		#box:before {
			border: 1px solid white;
			content: '';
			width: 198px;
			height: 198px;
			position: absolute;
		}

		#box:after {
			content: '';
			position: absolute;
			width: 196px;
			height: 196px;
			border: 1px solid #bbbbbb;
			left: 1px; top: 1px;
		}
	</style>

</head>
<body>
	<div id="box"></div>
</body>
</html>

In short, any browser that supports the :before and :after psuedo-elements (all major browsers) can take advantage of this effect. Of course, there are alternatives, including the use of box-shadow, as well as adding additional mark-up to the page; however, this is clean solution that you should definitely consider. Thanks for watching!

 
 

CSS Sprites2 – It’s JavaScript Time

23 Aug
In 2004, Dave Shea took the CSS rollover where it had never gone before. Now he takes it further still—with a little help from jQuery. Say hello to hover animations that respond to a user's behavior in ways standards-based sites never could before.

 

Hide Your Shame: The A List Apart Store and T-Shirt Emporium is back. Hot new designs! Old favorites remixed! S, M, L, XL. Come shop with us!

 
Comments Off on CSS Sprites2 – It’s JavaScript Time

Posted in Uncategorized