CSS performance: UI with fewer images


From phpied.com

Dec 23 This post is the one-before-last article in the 2009 performance advent calendar experiment.

Often performance improvements come with their drawbacks, sometimes improving performance causes pains in other parts of the development process or strips stuff from the final product. Sometimes there’s even a conflict where you have to pick: slow, unusable and beautiful or fast and looking like hacked with a blunt axe. But it doesn’t have to be this way.

This post outlines some approaches to achieving common UI elements using CSS tricks in as many browsers as possible while using as fewer images as possible. Some of the tricks are brand new, some are very, very old, IE5.5. old. They all have in common the “fewer or no images” mantra. Using fewer images comes with some pronounced benefits:

  • less time spent in Photoshop
  • lighter page, less HTTP requests, less image payload
  • fewer elements in the sprite to maintain (and sometimes fewer sprites) which means longer lived sprites with fewer updates and cache invalidation
  • generally easier maintenance – it’s much easier to change a color value than to update and push a new image version

Sometimes some browsers may not be fully supported but that’s ok – as long as there’s progressive enhancement and the basic page is usable, people rarely notice 1px glows and other ornaments.

So let’s get started. BTW, a test page with the stuff discussed in the post is here.

Rounded corners

Yep, let’s tackle the biggie.

Forget rounded corners in browser that don’t support border-radius. Period. It may be hard to argue this case, but definitely try. Doing rounded corners any other way than border-radius is a pain – it adds markup bloat, it makes you create more images or sprite elements. It's tougher to update. Just forget it. Forget rounded corners in IE < 9 (as rumor has it border-radius is coming to IE9). People may argue that IE is important for your audience. No doubt that's true, but rounded corners are not so important for the audience. Show your designer Yahoo Search results page – the sidebar on the left-hand side. Not very rounded in IE. Do you think this was an easy battle – losing rounded corners in IE for such a high-profile site? Ask the man who won the battle ;)

So starting with a normal module – head, body and border:

rounded1 CSS performance: UI with fewer images

The markup – nice and clean:

  <div class="module">
    <div class="hd"><h3>This is the header</h3></div>
    <div class="bd">
      <p>Here comes the content</p>
      <p>Here comes some more</p>
      <p>You can never have too much content, because
         content is king, right?
      </p>

    </div>
  </div>

Some fairly simple border radius to support Firefox, Webkit (Safari, Chrome, iPhone…) and, since a few days ago, Opera 10.5 alpha:

.module {
  -moz-border-radius: 9px;
  -webkit-border-radius: 9px;
  border-radius: 9px;
}

Result:

rounded2 CSS performance: UI with fewer images

This is it! Easy-peasy, lemon squeezy.

Now, it’s a little annoying to write three declarations for the same thing, but, hey – beats images and extra markup hands down. Also annoying are the differences when setting individual corners (-moz-border-radius-topleft is -webkit-border-top-left-radius). In this case we need to also round the header (class .hd) so it doesn’t bleed through the beautifully rounded corners:

.hd {
  -moz-border-radius: 8px 8px 0 0;
  -webkit-border-top-left-radius: 8px;
  -webkit-border-top-right-radius: 8px;
  border-radius: 8px 8px 0 0;
}

Verdict:

  • Full support: Firefox, Safari, Chrome, Opera 10.5
  • Fallbacks: IE (corners are not rounded)

Drop shadows and glows

Another favorite effect designers love – dropping shadows. It’s easy to enhance that existing .module without any new images:

.module {
  /* offset left, top, thickness, color with alpha */
  -webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5);
  -moz-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5);
  box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5);
  /* IE */
  filter:progid:DXImageTransform.Microsoft.dropshadow(OffX=5, OffY=5, Color='gray');
  /* slightly different syntax for IE8 */
  -ms-filter:"progid:DXImageTransform.Microsoft.dropshadow(OffX=5, OffY=5, Color='gray')";
}

And now our module casts a shadow:

shadow1 CSS performance: UI with fewer images

Now two notes for IE: first the shadow doesn’t have alpha so it’s not as nice and second, this filter may not play along with other filters in the same module. But the shadow is cast and that’s a check for IE too, even IE5.5!

shadow2 CSS performance: UI with fewer images

You may notice that in this case we basically need to more or less repeat the same declaration three times and the IE declaration two times. This is irksome, but hopefully keeping the strings close together should help gzip compression.

As for glowing, it’s the same thing in FF, Webkit, Opera, only without any offset. For IE, there’s a different filter called glow:

.glow {
  -webkit-box-shadow: 0 0 10px rgba(50, 50, 50, 0.8);
  -moz-box-shadow: 0 0 10px rgba(50, 50, 50, 0.8);
  box-shadow: 0 0 10px rgba(50, 50, 50, 0.5);
  filter:progid:DXImageTransform.Microsoft.glow(Strength=5, Color='gray');
  -ms-filter:"progid:DXImageTransform.Microsoft.glow(Strength=3, Color='gray')";
}

I added these declaration to a new class .glow so I can add the class name to modules that need to glow. The result:

glow CSS performance: UI with fewer images

The result as it glows in IE:

glowie CSS performance: UI with fewer images

Now you see why I added only 3 pixels glow in IE and whole 5 in the rest. The IE glow is a little .. interesting. Also in IE8 (could be my VM, in IE6 XP no VM all looks OK) the glow seems to move slightly when you hover over the module.

Verdict for shadows and glows:

  • Full support: FF, Safari, Chrome, Opera, IE5.5 and up

More info:

Gradients

Ah, gradients. Sometimes so subtle that we, muggles and other mere mortals, don’t see them even when we try our hardest. But for the designer they could be life/death situation.

Let’s make the head (class .hd) of our module a gradient without any images:

.hd {background-image: -moz-linear-gradient(top, #641d1c, #f00);
  background-image: -webkit-gradient(linear, left top, left bottom, from(#641d1c), to(#f00));
  filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#ff641d1c,endColorstr=#ffff0000);
  -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ff641d1c,endColorstr=#ffff0000)";
}

The result:

gradient CSS performance: UI with fewer images

What a beautiful (code-speaking, of course, not so sure about visually beautiful) module. It has rounded corners, drop shadows and a gradient and so far we haven’t used even a single image. Which means this reddish module can become blue, green or, god forbid, pink – with a single tweak in the code, the CMS or the user preferences (if you’re building a social network for example).

Gradients verdict:

  • Full support: FF, Safari, Chrome, IE
  • Fallbacks: Opera (solid color)

More info:

… and RGBA for all

Being able to set the transparency of the background without affecting the transparency of the foreground (the text) is quite handy. That’s why there’s rgba() in CSS (red, green, blue, alpha). IE is not yet supporting it, but we can use the gradient filter which does support transparency. In this case we don’t need the actual gradient so we set start and end color to the same thing. Also the background: transparent is needed for the whole thing to work in IE:

.rgba {
  background-color: transparent;
  background-color: rgba(200,200,200,0.8);
  filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99dddddd,endColorstr=#99dddddd);
  -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99dddddd,endColorstr=#99dddddd)";
}

The result is pleasantly cross-browser:

rgba CSS performance: UI with fewer images

RGBA verdict

  • Full support: Firefox, Safari, Opera, Chrome, IE

Rotating images

It happens that sometimes you use the same image only flipped. For example open/close thingies, menus and such. How about reusing the same image and rotating it with CSS?

.arrow {background: url(arrow.png) no-repeat; display: block; float: left; width: 33px; height: 33px;}
.right{ /* this is the original image*/ }
.left {
  -moz-transform: rotate(180deg);-webkit-transform: rotate(180deg); -o-transform: rotate(180deg);
  filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2);
  -ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2)";}
.up {
  -moz-transform: rotate(270deg);-webkit-transform: rotate(270deg); -o-transform: rotate(270deg);
  filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
  -ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=3)";}
.down {
  -moz-transform: rotate(90deg);-webkit-transform: rotate(90deg); -o-transform: rotate(90deg);
  filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);
  -ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=1)";
}

Here’s the result. Single image:

Arrow

Result:

rot fs8 CSS performance: UI with fewer images

the HTML:

<span class="arrow right"></span>
<span class="arrow left"></span>
<span class="arrow up"></span>
<span class="arrow down"></span>

You may notice that the CSS could be quite verbose for saving such small images. It’s highly recommended you add the rotation code to a class and use the class name when necessary instead of repeating the same long declaration for every use case or image. Then pray to the gods of compression that this thing gzips well ;)

Verdict

  • Full support: Firefox, IE, Safari, Opera, Chrome

Multiple UI elements with the same background image

The last few tricks have something in common – they each use one background image. The background images are very small – usually around 100 bytes. The tiny image has some transparency to it and is placed as a background-image which sits on top of a background-color. Because of the transparency, the background color shines through, but differently depending on the transparency level of the image above it.

The result is – different UI elements with different colors (and even different hover colors) which can be part of CMS or part of user’s skinning and they all reuse the same tiny background. So what can we do this way? A lot of interesting background effects, but here’s a few.

Glossy buttons

Here’s the end result:

buttons CSS performance: UI with fewer images

All these buttons share the same background image. The image is 1×1000 and repeated horizontally. The 1000 is just to be safe, very safe, because 50, 100 or 1000 doesn’t affect the file size which just a mere 100 bytes. The upper half of the image is a little less transparent. The lower half is 100% transparent. When placed on top of the solid color the whole thing looks shiny and glossy. And you can change the color any way you like.

The HTML:

<p class="button">button1<p>
<p class="button button2">button2<p>
<p class="button button3">button3<p>
<p class="button button4">button4<p>
<p class="button button5">button5<p>
<p class="button button6">button6<p>

And the CSS can’t be simpler:

.button {
  background-image:url(http://tools.w3clubs.com/mask/mask.php?x=1000&type=h);
  background-position: center;
}
.button:hover {background-color: #F29222;}
.button2 {background-color: #A41D1C;}
.button3 {background-color: #0F6406;}
.button4 {background-color: #333f79;}
.button5 {background-color: black;}
.button6 {background-color: orange; color: black;}

Actually in the test page I have inlined the image with data URI to save the whole HTTP request for such a teeny image.

As you can see in the URL of the background, I’ve done a little script to generate some background images:
http://tools.w3clubs.com/mask/mask.php?x=1000&type=h
The image generator’s source code is right here.

Stripes

Same technique – but used to generate striped background:

stripes CSS performance: UI with fewer images

It’s basically the same code, only using a different call to the image generator to give us a different background image.

HTML:

  <div class="module stripe earth glow">
    <div class="bd">
      <p>striped background</p>
    </div>

  </div>

  <div class="module stripe tech glow">
    <div class="hd phony stripe"><h3>stripity-stripes</h3></div>
    <div class="bd">
      <p>striped background with the same background image</p>
    </div>
  </div>

CSS:

.stripe {background-image: url(http://tools.w3clubs.com/mask/mask.php?type=stripe);}
.earth  {background-color: olive;}
.tech   {background-color: #bbb;}
.phony  {background-color: #0F6406;}

Again, this image can be a data URI so we save the single HTTP request.

And another gradient

So if you don’t like the previously discussed way to do gradients, here’s another one. The same trick with the solid color background and a semi-transparent image on top.

Result:

grimage CSS performance: UI with fewer images

The background images as generated by the service are:
// lighter at the top
http://tools.w3clubs.com/mask/mask.php?type=gradient
// darker at the top
http://tools.w3clubs.com/mask/mask.php?type=gradient&flip=1

Again, you can see the test page here and the source for the image generation is here.

For yet another example of this technique check my post on this (abandoned) blog phonydev.com. There I take an image and a mask image generated by the same script and overlay to achieve an iPhone-like glossy button.

iphone glossiness

Thanks!

Kind of long post, but I hope you’re excited about removing a bunch of images from your future designs. If I’ve omitted some details, please let me know in the comments.



CSS Techniques I Wish I Knew When I Started Designing Websites


From Noupe

By Tim Wright and TJ Kelly

CSS is the best thing to happen to the web since Tim Berners-Lee. It’s simple, powerful, and easy to use. But even with all its simplicity, it hides some important capabilities. Ask any designer, and they’ll tell you that the majority of their code headaches are caused and ultimately solved by CSS.

All designers at some point in their career go through the process of encountering a weird display issue, searching for a resolution, and discovering a trick, technique, or hack could have saved them hours of frustration—if they had only known when they started.

We’ve put together a list of the most frustrating and time-consuming CSS headaches and, more importantly, their solutions (along with examples and further resources). I hope this list will help you save some gray hairs. As for me, I think I feel some coming in right now…

Resets & Browser Inconsistencies

Not all browsers are created equal. In fact, every browser is different. What is the default margin, padding, or font-size of a <p> element? You might be surprised at the wide range of values. To handle the differences between browsers, many of us want to level the playing field and start from scratch, by using CSS reset styles.

The early stages of resets, designers dealt with differing margin and padding values, using a global reset:

* { margin: 0; padding: 0; }

But, as more people used and discussed resets, it became clear that resetting only margin & padding wasn’t enough (and, applying the above rule to every element is taxing on the rendering engine). Thanks to the work of Eric Meyer and other CSS pioneers, a better, more complete collection of reset rules was created:

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: "" "";
	}

As important as it is to note which elements are included in the most popular CSS reset available today .It’s also important to note some of the elements that are deliberately excluded from this list:

  • input
  • button
  • hr

These elements were excluded because their cross-browser differences are so vast that you would have to completely unstyle them to create a "bulletproof" element. They’re so weird, that even then, there’s no guarantee.

Resources for Resets

Box Model — Margin, Padding & Borders

The box model is the basis for all layouts. It governs the dimensions & spacing of the elements on a page. To understand it, we have to understand the difference between block-level elements and inline elements.

Block-level elements, by default, take up the entire width of their containing element and the height of the default line-height. They will stack up underneath each other, top-to-bottom. Therefore, by default, they will take up their own line on a page. Some block-level elements are: <div>, <pre>, <p>, <ul>, <ol>, <li>, etc.

Inline elements are, just as their name implies, in-line. They will stack up next to each other, left-to-right. When given content, they will take up the exact width and height of that content. Given no content, they will collapse down and have no width or height. Some in-line elements are: <img>, <em>, <strong>, <a>, <span>, etc.

All HTML block-level elements have five spacing properties: height, width, margin, padding, and border (inline elements have them too, they just work a bit differently). Width and height are tricky attributes, as they require a bit of calculation. When measuring an element’s width, designers must consider the entire box.

In the example below, the box has a total width of 260px. The margin, padding, and border are 30px each (remember, that’s 30px on top, 30 on bottom, 30 right, and 30 left). So, in this example, the margin takes up 60 pixels of the box’s width. Likewise, the border and padding consume 60px each. All together, the margin, border, and padding amount to 180 pixels of the box’s total width.

Box-model in CSS Techniques I Wish I Knew When I Started Designing Websites

We know that the box’s total width is 260px, but in CSS the width attribute refers to the content area on the inside of the box. So, for this example, we have to subtract 180 pixels (for margin, border, and padding) from 260 (total box width), leaving us with a content area of 80px. Therefore, our CSS looks like this:

div {
  margin:30px;
  border:30px solid yellow;
  padding:30px;
  width:80px;
  height:80px;
}

Extras

  1. All of the examples and rules we’re discussed for the width property also apply to height.
  2. margin can support negative values. Use them cautiously but they can prove to be very strong design elements.
  3. Don’t forget the units with the box model. Only a zero-value (margin:0;) can be written without a unit specified.

Resources for CSS Box Model

Dimensions — Width, Height, Min & Max

Now that we understand how to use width and height in unison with the box model, let’s look at some of the flexibility of CSS dimensions. Modern browsers support min- and max-width (and the same for height), allowing us to get creative with dimensions and create flexible layouts.

Width/height specify the space an object should occupy. They can be measured in pixels (10px), ems (10em) and percentages (10%), as well as a few other units. Defining a width or height for an element will force that element to keep those dimensions, regardless of the content inside it. So, if our content is too big for its container, it will be cut off, hiding the bottom of our content (or just look really messed up).

Min-width & min-height

Giving an element a min-width or min-height will set the element to our exact dimension by default. But, since we only provided a minimum dimension, as the content grows, the containing element will allowed to stretch and all of our content will remain visible.

Min-width & min-height can he useful for form elements like <input /> and <textarea>. We can define them with a minimum width/height and let them expand as the user types.

In IE6, "height" acts the same way "min-height" does in modern browsers as a container will grow with content (something to be aware of when using building for IE6).

Max-width & max-height

If we give an element a max-width or max-height, it will collapse down to the size of our content by default. As our content grows, the container will stretch—until it reaches our maximum. Then our remaining content will be cut off or look really weird hanging of the bottom of a content block.

Max-width & max-height can be useful for browsing long lists (if you correctly manage your overflow – create scrolling if the list goes too long).

Using Max & Min width in IE6

Min & Max width are both great tools to have in your design arsenal, but unfortunately they don’t work in IE6, so what do we do? We usually lock down the width of our site instead of creating the ideal fluid layout we want, sacrificing user experience for out of date browsers.

Luckily, we can use a short JavaScript command targetting IE to accomplish a nice fluid layout with max & min widths in IE6:

#page-wrap{
min-width:800px;
max-width:1000px;
width:expression(document.body.clientWidth < 800? "800px" : document.body.clientWidth > 1000? "1000px" : "auto");
}

In the above example, you can see that the smallest width for this page is 800px, and the largest is 1000px; not much of a flex, but the concept can be applied to any element.

And if you only wanted to use min-width:

#page-wrap{
min-width:800px;
width:expression(document.body.clientWidth < 800? "800px": "auto" );
} 

Resources for dimensions

Floats & Clearing

A float will place an element outside the normal flow of elements and moves the element right or left until it reaches the margin or padding of another block-level element. Float and clear are some of the most powerful—and the most misunderstood—properties in CSS. To understand it, we must refer back to block-level vs. inline elements.

Applying float to an element will automatically make it a block-level element. This means two things: 1) by default, all floated elements (even <span> and <strong>) will behave like block-level elements, 2) Giving an element both float:left; and display:block; is redundant and unnecessary. Also, using display:inline on a floated image is actually a very popular method of fixing many cross-browser quirks.

Floating a div to clear a div

Floating a div to clear a div is one of those things you stumble upon with some experimenting and frustration. What basically happens is that you can apply a float to a parent element that contains other floated elements and they will all equalize and clear properly:

HTML
<div class="parent-element">
     <div class="floating-element"></div><!--/.floating-element-->
     <div class="floating-element"></div><!--/.floating-element-->
     <div class="floating-element"></div><!--/.floating-element-->
</div><!--/.parent-element-->
CSS
.floating-element   { float:left;width:33%; }
.parent-element     { float:left; }

And, of course you’ll need some content in there to fill out the divs.

There are a lot of clearing techniques you can use to clear floated divs. Some require extra markup, some don’t work in IE 6 and some are great, but don’t apply to every situation. What did I wish I knew about clearing floats when I started? Everything.

Resources for clear and float

Conditional Comments

Back in 2004, when I really got into full-time Web design I used a lot of IE hacks and techniques to patch together sites in an attempt to achieve some level of cross browser compatibility. This can cause very bloated and slow loading style sheets. Everyone was doing it, heck, there were even articles about how to best organize your IE hacks.

Little by little the design community discovered a hidden gem buried within the functionality of the Triton rendering engine (Internet Explorer). You could use IE specific HTML to target specific versions of the browser and then load a special style sheet just to deal with those issues.

<!--[if IE]>
Target all versions of IE
<![endif]-->

<!--[if lte IE 7]>
Target all versions of IE that are less than or equal to "7"
<![endif]-->

<!--[if IE 6]>
Target IE 6
<![endif]-->

Using conditional comments to target IE and cut out your hacks, will slim down your main style sheet, and help load the page quicker in browsers that don’t need the correction code.

Resources for Conditional Comments

Overflow & Zoom

Like many designers, if there’s time to be wasted on a project, it usually gets wasted dealing with IE 6 and some of it’s weirder quirks. This is where overflow and zoom have helped me a great deal.

Overflow

Many-a-times when I’ve encountered a serious layout issue, a simple application of overflow:hidden on the offensive div would solve the problem. It’s difficult to pin point specific issues for this, but it can happen in any browser (I just had it happen in Safari a couple weeks ago) and the overflow property can provide a quick solution to your cross browser woes.

Zoom

To my surprise, the zoom property is not very well know, but a very powerful tool in dealing with cross browser issues; particularly IE 6/7. Zoom is a proprietary IE property that actually does effect the zoom level of a page (if you set the zoom to 2 you’ll see everything get bigger). As a site effect it also triggers hasLayout on the offending element, and fixes a lot of layout issues. Try it out, it actually saves a lot of time.

body { zoom:1; }

Since hasLayout won’t trigger in any other browser, it’s generally thought to be safe to put zoom in your main style sheet, but it you’re doing IE specific work anyway, I’d advise putting it in with the rest of the IE CSS just in case there are any problems in the future, "future proofing".

Resources for Overflow & Zoom

When CSS isn’t the Answer

Believe it or not, CSS is not always the answer. Especially now when we live on a Web that is in the middle of the biggest browser war to date. Sometimes CSS just doesn’t do everything we want on as many platforms as we need it to.

Spending hours searching for a CSS solution to a non-critical element that can be easily fixed with JavaScript usually just isn’t worth it. Now that we have great libraries like jQuery readily available to us, anyone well versed in CSS can quickly pick up JavaScript. And let me tell you… if I new more about JavaScript when I started it would have saved me a lot of time and frustration.

Conclusion

There are a lot of little idiosyncrasies with CSS that you’ll encounter over time with experience and frustration, but we’re looking for ways to minimize that frustration. The best advice I can give someone in dealing with CSS is the same advice someone gave me when I was in college: go to class. If you read the blogs, keep up with all the information and learn everything you can you’ll save a lot of time when you do encounter the inevitable rendering problem. To be honest, half the battle is knowing what a bug is called so you can Google it.

But of course an article like this always poses the question: What do you YOU wish you knew when you started?

About the Author

Tim Wright is a web designer/developer and blogger. He has been an advocate for Web standards and accessibility since 2004. You can find more of his writing at CSSKarma or follow Tim on Twitter.

TJ Kelly is a web designer/developer from Boston, MA, USA. He specializes in UX/UI design, CSS/jQuery, WordPress, SEO, and Social Media. He’s passionate about W3C Web Standards, accessibility, and usability. Check out his blog and portfolio at www.tjkelly.com and follow TJ on Twitter.

 CSS Techniques I Wish I Knew When I Started Designing Websites  CSS Techniques I Wish I Knew When I Started Designing Websites  CSS Techniques I Wish I Knew When I Started Designing Websites  CSS Techniques I Wish I Knew When I Started Designing Websites


10 Usability Crimes You Really Shouldn’t Commit


From Line25

Over time certain conventions and best practices have been developed to help improve the general usability of websites during their design and build. This roundup of ten usability crimes highlights some of the most common mistakes or overlooked areas in web design and provides an alternative solution to help enhance the usability of your website.

Crime 1: Form labels that aren’t associated to form input fields

crime1 10 Usability Crimes You Really Shouldn’t Commit

Using the ‘for’ attribute allows the user to click the label to select the appropriate input fields within a form. This is especially important for checkboxes and radio fields to give a larger clickable area, but it’s good practice all round.

Crime 2: A logo that doesn’t link to the homepage

crime2 10 Usability Crimes You Really Shouldn’t Commit

Linking the logo of a website to the homepage has become common practice and is now second nature for (most) web surfers to expect the logo to head back home. It’s also worth mentioning the logo should appear in the top left.

Crime 3: Not specifying a visited link state

crime3 10 Usability Crimes You Really Shouldn’t Commit

Visited link states do exactly as they say on the tin. It’s not the most advanced CSS selector, but it’s one that is often overlooked. Give users a visual clue as to which link has already been clicked.

Crime 4: Not indicating an active form field

crime4 10 Usability Crimes You Really Shouldn’t Commit

You can use the ‘:focus’ selector on lots of elements, but it’s super handy when used on inputs and textareas to indicate that the field is active. Add CSS styling such as a highlighted border, or a subtle change to the background color.

Crime 5: An image without an alt description

crime5 10 Usability Crimes You Really Shouldn’t Commit

This is straying a little into the realm of accessibility, but it’s still an important consideration! Remember to always add a descriptive alt attribute to your images, unless of course they are used for decorative purposes, then the ALT attribute can be left empty (but should still exist!). When using an image as a link, enter a description of where the link goes.

Crime 6: A background image without a background color

crime6 10 Usability Crimes You Really Shouldn’t Commit

It’s common to use background images behind passages of text, but it’s worth remembering that if background images are disabled by the user, there needs to be a similar tone in the form of a background colour to avoid the text becoming unreadable.

Crime 7: Using long boring passages of content

crime7 10 Usability Crimes You Really Shouldn’t Commit

There’s nothing more off-putting than landing on a webpage that’s laid out as a continuous passage of text. Break up your content with images, headings and clear sections to make it easier to scan, read and digest.

Crime 8: Underlining stuff that isn’t a link

crime8 10 Usability Crimes You Really Shouldn’t Commit

Everyone knows that text that’s underlined, or is a different colour is likely to be a link. Don’t go confusing people by throwing in underlined text elsewhere! To draw attention to a certain word, try using the strong or emphasize tags instead.

Crime 9: Telling people to click here

crime9 10 Usability Crimes You Really Shouldn’t Commit

The words click here have been around since the dawn of the Internet, but have been shunned aside in favour of more usable options. Using the words click here requires the user to read the whole sentence to find out what’s going to happen. Instead, describe what’s going to happen in the actual anchor link text.

Crime 10: Using justified text

crime10 10 Usability Crimes You Really Shouldn’t Commit

This is another tip that’s heading a little deeper into accessibility but is also an important point to consider. Justified text might look at neat and square to the eye, but it can generate some real readability problems, particularly for Dyslexic users who can find it troublesome to identify words due to the uneven spacing of justified paragraphs.

Similar Posts

 10 Usability Crimes You Really Shouldn’t Commit  10 Usability Crimes You Really Shouldn’t Commit  10 Usability Crimes You Really Shouldn’t Commit  10 Usability Crimes You Really Shouldn’t Commit


Mastering CSS Coding: Getting Started


From Smashing Magazine

smashing magazine advertisement Mastering CSS Coding: Getting Started
 Mastering CSS Coding: Getting Started  Mastering CSS Coding: Getting Started  Mastering CSS Coding: Getting Started

spacer Mastering CSS Coding: Getting Started

astering CSS Coding: Getting Started (via @smashingmag) -

CSS has become the standard for building websites in today’s industry. Whether you are a hardcore developer or designer, you should be familiar with it. CSS is the bridge between programming and design, and any Web professional must have some general knowledge of it. If you are getting your feet wet with CSS, this is the perfect time to fire up your favorite text editor and follow along in this tutorial as we cover the most common and practical uses of CSS.

Overview: What We Will Cover Today

We’ll start with what you could call the fundamental properties and capabilities of CSS, ones that we commonly use to build CSS-based websites:

  1. Padding vs. margin
  2. Floats
  3. Center alignment
  4. Ordered vs. unordered lists
  5. Styling headings
  6. Overflow
  7. Position

Once you are comfortable with the basics, we will kick it up a notch with some neat tricks to build your CSS website from scratch and make some enhancements to it.

  1. Background images
  2. Image enhancement
  3. PSD to XHTML

1. Padding vs. Margin

Most beginners get padding and margins mixed up and use them incorrectly. Practices such as using the height to create padding or margins also lead to bugs and inconsistencies. Understanding padding and margins is fundamental to using CSS.

What Is Padding and Margin?

Padding is the inner space of an element, and margin is the outer space of an element.

The difference becomes clear once you apply backgrounds and borders to an element. Unlike padding, margins are not covered by either the background or border because they are the space outside of the actual element.

Take a look at the visual below:

Box Model

Padding/Margin Values
Margin and padding values are set clockwise, starting from the top.

Practical example: Here is an <h2> heading between two paragraphs. As you can see, the margin creates white space between the paragraphs, and the padding (where you see the background gray color) gives it some breathing room.

Box Model - Example

Margin and Padding Values

In the above example of the heading, the values for the margin and padding would be:

margin: 15px 0 15px 0;
padding: 15px 15px 15px 15px;

To optimize this line of code further, we use an optimization technique called “shorthand,” which cuts down on repetitive code. Applying the shorthand technique would slim the code down to this:

margin: 15px 0; /*--top and bottom = 15px | right and left = 0 --*/
padding: 15px; /*--top, right, bottom and left = 15px --*/

Here is what the complete CSS would look like for this heading:

h2 {
background: #f0f0f0;
border: 1px solid #ddd;
margin: 15px 0;
padding: 15px;
}

Quick Tip

Keep in mind that padding adds to the total width of your element. For example, if you had specified that the element should be 100 pixels wide, and you had a left and right padding of 10 pixels, then you would end up with 120 pixels in total.

100px (content) + 10px (left padding) + 10px (right padding) = 120px (total width of element)

Margin, however, expands the box model but does not directly affect the element itself. This tip is especially handy when lining up columns in a layout!

Additional resources:

2. Floats

Floats are a fundamental element in building CSS-based websites and can be used to align images and build layouts and columns. If you recall how to align elements left and right in HTML, floating works in a similar way.

According to HTML Dog, the float property “specifies whether a fixed-width box should float, shifting it to the right or left, with surrounding content flowing around it.”

Float

The float: left value aligns elements to the left and can also be used as a solid container to create layouts and columns. Let’s look at a practical situation in which you can use float: left.

Float to Create Layouts

The float: right value aligns elements to the right, with surrounding elements flowing to the left.

Quick tip: Because block elements typically span 100% of their parent container’s width, floating an element to the right knocks it down to the next line. This also applies to plain text that runs next to it because the floated element cannot squeeze in the same line.

Floating right bug

You can correct this issue in one of two ways:

  1. Reverse the order of the HTML markup so that you call the floated element first, and the neighboring element second.
    Floating right fix
  2. Specify an exact width for the neighboring element so that when the two elements sit side by side, their combined width is less than or equal to the width of their parent container.
    Floating right fix

Internet Explorer 6 (IE6) has been known to double a floated element’s margin. So, what you originally specified as a 5-pixel margin becomes 10 pixels in IE6.

Double Margin Bug - IE6

A simple trick to get around this bug is to add display: inline to your floated element, like so:

.floated_element {
float: left;
width: 200px;
margin: 5px;
display: inline; /*--IE6 workaround--*/
}

Additional resources:

3. Center Alignment

The days of using the <center> HTML tag are long gone. Let’s look at the various ways of center-aligning an element.

Horizontal Alignment

You can horizontally align text elements using the text-align property. This is quite simple to do, but keep in mind when center-aligning inline elements that you must add display: block. This allows the browser to determine the boundaries on which to base its alignment of your element.

.center {
text-align: center;
display: block; /*--For inline elements only--*/
}

To horizontally align non-textual elements, use the margin property.

The W3C says, “If both margin-left and margin-right are auto, their used values are equal. This horizontally centers the element with respect to the edges of the containing block.”

Horizontal alignment can be achieved, then, by setting the left and right margins to auto. This is an ideal method of horizontally aligning non-text-based elements; for example, layouts and images. But when center-aligning a layout or element without a specified width, you must specify a width in order for this to work.

To center-align a layout:

.layout_container {
margin: 0 auto;
width: 960px;
}

To center-align an image:

img.center {
margin: 0 auto;
display: block; /*--Since IMG is an inline element--*/
}

Vertical Alignment

You can vertically align text-based elements using the line-height property, which specifies the amount of vertical space between lines of text. This is ideal for vertically aligning headings and other text-based elements. Simply match the line-height with the height of the element.

Line-height

h1 {
font-size: 3em;
height: 100px;
line-height: 100px;
}

To vertically align non-textual elements, use absolute positioning.

The trick with this technique is that you must specify the exact height and width of the centered element.

With the position: absolute property, an element is positioned according to its base position (0,0: the top-left corner). In the image below, the red point indicates the 0,0 base of the element, before a negative margin is applied.

By applying negative top and left margins, we can now perfectly align this element both vertically and horizontally.

Absolute Position

Here is the complete CSS for horizontal and vertical alignment:

.vertical {
width: 600px; /*--Specify Width--*/
height: 300px; /*--Specify Height--*/
position: absolute; /*--Set positioning to absolute--*/
top: 50%; /*--Set top coordinate to 50%--*/
left: 50%; /*--Set left coordinate to 50%--*/
margin: -150px 0 0 -300px; /*--Set negative top/left margin--*/
}

Related articles:

4. Ordered vs. Unordered Lists

An ordered list, <ol>, is a list whose items are marked with numbers.

An unordered list, <ul>, is a list whose items are marked with bullets.

By default, both of these list item styles are plain and simple. But with the help of CSS, you can easily customize them.

To keep the code semantic, lists should be used only for content that is itemized in a list-like fashion. But they can be extended to create multiple columns and navigation menus.

Customizing Unordered Lists

Plain bullets are dull and may not draw enough attention to the content they accompany. You can fix this with a simple yet effective technique: remove the default bullets and apply a background image to each list item.

Here is the CSS for custom bullets:

ul.product_checklist {
list-style: none; /*--Takes out the default bullets--*/
margin: 0;
padding: 0;
}
ul.product_checklist li {
padding: 5px 5px 5px 25px; /*--Adds padding around each item--*/
margin: 0;
background: url(icon_checklist.gif) no-repeat left center; /*--Adds a bullet icon as a background image--*/
}

Custom List Items

Resources for list items:

Using Unordered Lists for Navigation

Most CSS-based navigation menus are now built as lists. Here is a breakdown of how to turn an ordinary list into a horizontal navigation menu.

HTML: begin with a simple unordered list, with links for each list item.

<ul id="topnav">
<li><a href="#">Home</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Portfolio</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>

CSS: we remove the default bullets (as we did when we made custom bullets) by specifying list-style: none. Then, we float each list item to the left so that the navigation menu appears horizontal, flowing from left to right.

ul#topnav {
list-style: none;
float: left;
width: 960px;
margin: 0; padding: 0;
background: #f0f0f0;
border: 1px solid #ddd;
}
ul#topnav li {
float: left;
margin: 0; padding: 0;
border-right: 1px solid #ddd;
}
ul#topnav li a {
float: left;
display: block;
padding: 10px;
color: #333;
text-decoration: none;
}
ul#topnav li a:hover {
background: #fff;
}

Additional resources:

5. Styling Headings

The heading HTML tag is important for SEO. But regular headings can look dull. Why not spice them up with CSS and enjoy the best of both worlds?

Once you have the main styling properties set for your headings, you can now nest inline elements to target specific text for extra styling.

Styling Headings

Your HTML would look like this:

<h1><span>CSS</span> Back to Basics <small>Tips, Tricks, &amp; Practical Uses of CSS</small></h1>

And your CSS would look like this:

h1 {
font: normal 5.2em Georgia, "Times New Roman", Times, serif;
margin: 0 0 20px;
padding: 10px 0;
font-weight: normal;
text-align: center;
text-shadow: 1px 1px 1px #ccc; /*--Not supported by IE--*/
}
h1 span {
color: #cc0000;
font-weight: bold;

}
h1 small {
font-size: 0.35em;
text-transform: uppercase;
color: #999;
font-family: Arial, Helvetica, sans-serif;
text-shadow: none;
display: block; /*--Keeps the small tag on its own line--*/
}

Additional typography-related resources:

6. Overflow

The overflow property can be used in various ways and is one of the most useful properties in the CSS arsenal.

What Is Overflow?

According to W3Schools.com, “the overflow property specifies what happens if content overflows an element’s box.”

Take a look at the following examples to see how this works.

Overflow

Visually, overflow: auto looks like an iframe but is much more useful and SEO-friendly. It automatically adds a scroll bar (horizontal, vertical or both) when the content within an element exceeds the element’s box or boundary.

The overflow: scroll property works the same but forces a scroll bar to appear regardless of whether or not the content exceeds the element’s boundary.

And the overflow: hidden property masks or hides an element’s content if it exceeds the element’s boundary.

Quick tip: have you ever had a parent element that did not fully wrap around its child element? You can fix this by making the parent container a floated element.

In some cases, though, floating left or right is not a workable solution — for example, if you want to center-align the container or do not want to specify an exact width. In this case, use overflow: hidden on your parent container to completely wrap any floated child elements within it.

Overflow

Additional resources:

7. Position

Positioning (relative, absolute and fixed) is one of the most powerful properties in CSS. It allows you to position an element using exact coordinates, giving you the freedom and creativity to design out of the box.

You have to do three basic things when using positioning:

  1. Set the coordinates (i.e. define the positioning of the x and y coordinates).
  2. Choose the right value for the situation: relative, absolute, fixed or static.
  3. Set a value for the z-index property: to layer elements (optional).

With position: relative, an element is placed in its natural position. For example, if a relatively positioned element sits to the left of an image, setting the top and left coordinates to 10px would move the element just 10 pixels from the top and 10 pixels from the left of that exact spot.

Relative positioning is also commonly used to define the new point of origin (the x and y coordinates) of absolutely positioned nested elements. By default, the base position of every element is the top-left corner (0,0) of the browser’s view port. When you give an element relative positioning, then the base position of any child elements with absolute positioning will be positioned relative to their parent element — i.e. 0,0 is now the top-left corner of the parent element, not the browser’s view port.

Relative Position

An element with a value of position: absolute can be placed anywhere using x and y coordinates. By default, its base position (0,0) is the top-left corner of the browser’s view port. It ignores all natural flow rules and is not affected by surrounding elements.

The base position of an element with a position: fixed value is also the top-left corner of the browser’s view port. The difference with fixed positioning is that the element will be fixed to its location and remain in view even when the user scrolls up or down.

The z-index property specifies the stack order of an element. The higher the value, the higher the element will appear.

Think of z-index stacking as layering. Check out the image below for an example:

z-index

Additional resources:

Adding Flavor With CSS

Now that you understand the basics, step up your game by adding a bit of flavor to your CSS. Below are some common techniques for enhancing and polishing your layout and images. We’ll also challenge you to create your own website from scratch using pure CSS.

9. Background Images

Background images come in handy for many visual effects. Whether you add a repeating background image to cover a large area or add stylish icons to your navigation, the property makes your page come to life.

Note, though, that the default print setting excludes the background property. When creating printable pages, be mindful of which elements have background images and include image tags.

Using Large Backgrounds

With monitor sizes getting bigger and bigger, large background images for websites have become quite popular.

Check out this detailed tutorial by Nick La of WebDesigner Wall on how to achieve this effect:

Large Backgrounds in Web Design

Also be sure to read the article on Webdesigner Depot about the “Do’s and Don’ts of Large Website Backgrounds.”

Text Replacement

You may be aware that not all standard browsers yet support custom fonts embedded on a website. But you can replace text with an image in various ways. One rather simple technique is to use the text-indent property.

Most commonly seen with headings, this technique replaces structured HTML text with an image.

h1 {
background: url(home_h1.gif) no-repeat;
text-indent: -99999px;
}

You may sometimes need to specify a width and height (as well as display: block if the element is inline).

.replacethis {
background: url(home_h1.gif) no-repeat;
text-indent: -99999px;
width: 100%;
height: 60px;
display: block; /*--Needed only for inline elements--*/
}

Articles on text replacement:

CSS Sprites

CSS Sprites is a technique in which you use background positioning to show only a small area of a larger single background image (the larger image being actually multiple images laid out in a grid and merged into one file).

CSS Sprites

CSS Sprites are commonly used with icons and the hover and active states of images that have replaced links and navigation items.

CSS Sprites

Why use CSS Sprites? CSS Sprites save loading time and cut down on CSS and and HTTP requests. To learn more about CSS Sprites, check out the resources below!

Articles on CSS Sprites:

10. Image Enhancement

You can style images with CSS in various ways, and some designers have made a lot of effort to create very stylish image templates.

One simple trick is the double-border technique, which does not require any additional images and is pure CSS.

Double Border Technique

Your HTML would look like this:

<img class="double_border" src="sample.jpg" alt="" />

And your CSS would look like this:

img.double_border {
border: 1px solid #bbb;
padding: 5px; /*Inner border size*/
background: #ddd; /*Inner border color*/
}

Nick La of WebDesigner Wall has a great tutorial on clever tricks to enhance your images. Do check it out!

CSS Sprites

11. PSD to HTML

Now that you have learned the fundamentals of CSS, it’s time to test your skill and build your own website from scratch! Below are some hand-picked tutorials from the best of the Web.

Conclusion

Developing a strong foundation early on is critical to mastering CSS. Given how fast Web technology advances, there is no better time than now to get up to speed on the latest standards and trends.

Hopefully, the techniques we’ve covered here will give you a head start on becoming the ultimate CSS ninja. Good luck, stay hungry and keep learning!

(al)


© Soh Tanaka for Smashing Magazine, 2009. |
Permalink |
151 comments |
Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine

Post tags:



© 2009 Jeremiah Altepeter

Valid XHTML 1.0 Strict! Valid CSS!
Made with Notepad++ Powered by Wordpress Hosted with 1&1 Get Chrome