Archive for the 'Design' Category

Feb 09 2008

CSS Best Practices

CSS Best Practices is the topic that I had been planning to write on for months. As CSS is the order of the day as far as web related UI is concerned, more people are moving to it. CSS isn’t always easy to deal with. CSS coding can sometimes become a nightmare, particularly if you’re not sure which selectors are applied to document elements. CSS Best Practices covers some important and easy to remember tricks and tips to better manage, organise and develop your CSS Snippets.

Use a browser reset

One of the most common mistakes that designers fall victim to when it comes to CSS is not resetting their browser defaults. This leads to inconsistencies in the appearance of your desing across different browsers. So before doing anything else, when coding a website, you should reset the styling. You can use a simple reset with the universal selector like this

* {

   margin:0;

   padding:0;

}

But using the universal selector is sometimes a bad idea as it is very heavy on the rendering agent to apply rules to every single element in the document.

One of the most popular browser resets is of CSS Reset by Eric Meyer. As Meyer says, “the styles should list all the actual elements to be reset and exactly how they should be reset.”

Another Browser Reset Library is Yahoo! UI Library: Reset CSS. It removes and neutralizes the default styling of html elements providing a foundation upon which you can explicity declare your extentions.

Another very useful CSS reset is CSS Global Styles Reset by Kyle Neath. A simple CSS Reset with some additional classes for better debugging.

Size text without using pixels

Web Designing best principles is to enable a site to withstand a user enlarging text and setting absolute text sizes is not a good practice. Instead we can size our text relative to the browser. Standard browser font size is 1em which is equal to 16px. A little web designer trick works around the issue and resets the font sizes for the entire site so that 1em is equal to 10 px.

body {

font-size:62.5%;

}

Simply throwing the font-size to 62.5% for the entire site does the trick. Now you can use em instead of pixels.

Organise your CSS Code

Organising your CSS code helps you with future maintainability of your site. You should make independent style sheets for different purposes and then linke them in your master stylesheet. Like you should maintain your typographic styles and structure selectors independently in different stylesheets and then link them together in your master stylesheet.

@import url("reset.css")

@import url("structure.css")

@import url("typography.css")

Make your code easy to read

While scanning through CSS, I came across a very nicely separated CSS coded probably by Rundle. It looked something like this:

h1 {}

h1#title { font-size:2em; }

div {}

div#error { color:#eee; }

This technique is very useful if you’re sharing code or working on a large site where you are using the same div tag in multiple places.

Document your code

This might be common sense to some of you but sometimes I look at CSS and it’s not documented at all. It is always a good practice to document your code or atleast provide a separate heading for a part of code as it makes working with code months or years later easier.

/**********************************/

/* Primary Navigation - Top Links */

/*********************************/

#nav {

border:1px solid #eee;

margin:10px auto;

padding:5px;

}/***************/

/* Search Box */

/**************/

#search-box {

position:absolute;

top:30px;

left:30px;

}

Keep containers to minimum

Avoid using too many Divs as it makes your document too much complex and tougher to handle. Avoid block level tags as much as possible and consider all options before using DIVs. New Developers to CSS often mistake DIVs for table cells and maximise their use to achieve the layout. Some people even style their headings with DIVs. Try using small tags or inline tags for goodness sake.

Use Shorthand CSS

Work smarter, not harder with CSS. You can wrap multiple properties within a single declaration by using special syntax. Avoid unnecessary properties as it directly effects your troubleshooting efforts.

Like instead of writing

margin-left:2px;

margin-top:3px;

margin-right:4px;

margin-bottom:5px;

You can write

margin:3px 4px 5px 2px;

Similarly we can use shorthand for border, background, padding, font and other properties.

Specify Units

Always specify units for the Property values unless it is 0. This a very common mistake among CSS beginners. In HTML you can get away with this but in CSS all length values should have a unit. While there’s no wrong in specifying a unit for 0 value, but for me it’s only a wastage of space.

padding:2px 3px 0 10px;

Working with Colors

In hexadecimal notation, a color is represented by three pairs of hexadecimal digits. You can write a color more efficiently by omitting every second digit like this.

#ffffff can be written as #fff

Similarly #ff3366 can be written as #f36

Another color related tip is that you can specify web safe colors by using only digits that are multiples of 3 for the red, green and blue.

Don’t redeclare inherited values

The values of many properties are inherited by any descendants of the element that you specify the property for. So there is no fun of redeclaring those properties again and again. Some of the commonly inherited properties are of font and color.

div {

font-size:2em;

color:#ef321d;

}

div.hello {

font-size:2em;

color:#ef23ef;

}

can be written as

div {

font-size:2em;

color:#ef321d;

}

div.hello {

color:#ef23ef;

}

Multiple Classes

You can assign multiple classes to a single HTML element. This allows you to write several rules that define different properties and only apply them as needed. The multiple classes (assuming .head & .head-about) can be applied to a single element like this.

<div class="head head-about">This is test for multiple classes</div>

Minimise CSS Hacks

Hacks are the tricks, usually non-standard, to overcome some browser limitations. Don’t use hacks unless it is a known and documented bug as it makes the future maintenance of the code very difficult in absence of proper documentation and standard coding design.

Define pseudo classes for links in the LoVe/HAte order

Link, Visited, Hover & Active, as the above represents. You should define your pseudo classes in this order

a:link { color: blue; }

a:visited { color: purple; }

a:hover { color: purple; }

a:active { color: red; }

Define generic font families

“When we declare a specific font to be used within our design, we are doing so in the hope that the user will have that font installed on their system. If they don’t have the font on their system, then they won’t see it, simple as that. What we need to do is reference fonts that the user will likely have on their machine, such as the ones in the font-family property below. It is important that we finish the list with a generic font type. [Getting into good coding habits]

p {

font-family: Arial, Verdana, Helvetica, sans-serif;

}

1 ID per page, many classes per page

“Check your IDs: Only one element in a document can have a certain value for the id attribute, while any number of elements can share the same class name. [..] Class and id names can only consist of the characters [A-Za-z0-9] and hyphen (-), and they cannot start with a hyphen or a digit (see CSS2 syntax and basic data types).” [Roger Johansson]

Horizontally Centering an element

It is very easy to center an element horizontally using HTML with the align attribute, but there is no such property in the CSS. Instead we use margin to center the element like this

margin:0 auto;

Here ‘auto’ automatically divides the space left on the sides of element into half and assigns each half on each side of the element

Conditional Comments of IE

IE versions less than 7 adhere to CSS standards very less and often create a nasty CSS bug or issue to deal with. You can come around the issue by creating a different style to address the issue and then include the style for only IE using IE conditional comments like this.

<!--[if IE]>

<link rel="stylesheet" type="text/css" href="ie.css" />

<![endif]-->

Jan 24 2008

PNG Transparency for Internet Explorer

Like GIFs and JPEGs, PNG images are ideal for web use. Like GIFs, the PNG is great for displaying small images with few colors, like logos and icons. Also, PNGs sport a few advantages over GIF images. Most notably, they support alpha transparency.

What is alpha-transparency? GIF files are only capable of displaying a pixel as either completely transparent or completely opaque: this is known as binary transparency. When an image contains alpha layers, however, parts of an image can be partially transparent. You can specify a level of transparency from 0 to 255.

PNGs thus have the potential for creating some interesting effects on a web page, like translucent background images and drop-shadows. But despite their advantages over GIFS, PNGs aren’t nearly as popular as GIFs web design, primarily because of the impression that PNGs don’t enjoy wide browser support.

This view on PNGs is a bit of a misconception.

While Internet Explorer for Windows 6 (IE6) and previous versions of IE don’t support PNGs’ alpha-transparency feature, all popular browsers can display PNGs.

While IE6- doesn’t explicitly support alpha-transparency out-of-the-box, if you will, there is a workaround that ensures PNG’s cross-browser compatibility.

Microsoft has a plethora of proprietary visual filters and transitions that are available to IE4+. These filters are designed to apply various multimedia affects (transition wipes, light effects and so on) to images in a web page that are viewed with IE. One of these image filters — AlphaImageLoader — lets you display a PNG with alpha-transparency in IE6.

You can employ this filter within the HTML of your page by creating a div element and embedding into it a bit of CSS:



<div style=”position:relative; height: 188px; width: 188px;

filter:progid:DXImageTransform.Microsoft.AlphaImageLoader

(src='images/image.png',sizingMethod='scale');”></div>

The key property here is the filter property. While filter is not valid CSS, it does allow you to apply the AlphaImageLoader filter to the image specified in the parentheses. However, since it isn’t standards-compliant, you may wish to apply this property only as needed (i.e., only when the page is being displayed in IE6-).

By combining this method, developers can build rich image-based designs with alpha transparency like they would for modern browsers like Safari, Firefox, and Internet Explorer 7 that all supports PNG alpha alpha transparency natively.

How to Include PNG Transparency in IE6

One available method for doing this is employing Angus Turnbull’s .htc script:

  1. First, download the .htc script at TwinHelix Designs. HTC is a
    scripting language
    only usable by Internet Explorer (because it was created by Microsoft) and this specific script contains applies the AlphaImageLoader filter to all images within a web page.
  2. After downloadign the script, upload the script to your Web server.
  3. Then, create (or download from TwinHelix) a blank gif file. This image file is 1×1 pixel with the color set as transparent. (Back in the 90s, these were called these gems “single pixel GIFs“). Within the .htc script, change the line that references the blank.gif file so that it points to the gif’s location on the server.
  4. Create a separate CSS file (we’ll name it ie.css), and include within in the following single line, referencing the location of the .htc file:
    
    
    img {
    
     behavior: url(iepngfix.htc);
    
    }
    
    

    The behavior property let’s you attach a script to some selector (in this case, all img elements). So, this CSS file attaches the .htc file to all of your images, thus applying the desired filter effect to every image within a web page.

  5. But, we only want to load this CSS file when the page is viewed in IE6-. To do this, just add the following conditional comment to your page’s header:
    
    
    <!--[if lte IE 6]>
    
    <link rel="stylesheet" type="text/css" media="screen"
    
    href="ie.css" />
    
    <![endif]-->
    
    

    Conditional comments like these are understood by IE. What the comment says is, “if the browser is IE6 or below, then read the lines within the comment tags. Otherwise, ignore them.” Conditional comments provide a convenient way of applying IE-specific HTML or CSS. Here, the ie.css stylesheet loads only if the page is displayed in IE6-, letting you apply the non-compliant CSS only when it’s absolutely necessary.

While a rather convoluted way to get transparent PNGs working in your web pages (although less convulted than, it does provide a method that is as standards-compliant as possible, giving you the freedom to include the beauty of semi-transparent layers in your designs.

Close
E-mail It