Some basic CSS tricks to remember

While working with the interface, in some points the developers get stuck. I’m going through some of these issues, which we can keep in mind to avoid some extra time spent on getting things done.

Placing Multiple DIV Elements Side by Side

Sometimes we need to place several DIV elements side by side. For this type of requirements, previously the practice was using tables. We know that TABLE element is rigid & doesn’t hold any floating positioning by default. But achieving that type of rigidness using DIV is also not that much of a trouble if you just keep a few simple things in mind.

Whenever you need to place DIVs side by side, all of them should have the float attribute in style to be set to left other than the last one. The last one should be set to float to right. May be we can think of having the display to be set as inline. But the problem with inline is you cannot set a width to an inline element. The inline component will always flow with the content.

Padding in Fixed With DIV

When you are setting some padding in a div with fixed width or height, you will see some abnormal behavior. Suppose following is the definition for a DIV style:

#ContentDiv
{
  width: 240px;
  height: 60px;
  padding: 15px 20px;
  border: 1px solid #CCC;
}

The expected style should naturally be a DIV with 240 px width, 60 px height having padding of 15 px on top & bottom, 20 px on left & right. But whenever you fill the DIV with your content, you’ll find that the DIV is getting a width of 280 px & height of 90 px.

When a DIV has a defined height/width & alsodefined some padding, the effective width & height turns to be the total of width/height added with the padding in the corresponding sides. So whenever using both padding & fixed height, this point should be kept in mind.

DIV inside DIV: Alignment

We often need to place a DIV inside another DIV or TD. When we try to center align a DIV within another DIV, you will find some problem. Setting text-align to center will do the work in IE, but you will find it of no use in Firefox browsers. In this case, the inner DIV needs to have a margin set. So what will you do? Set the margin by calculating your content of the inner DIV & width of the outer DIV? That will not work when you have the inner DIV content generated dynamically. The workaround here is setting the DIV styles as follows:

#OuterDIV
{
  width:160px;
}

#InnerDIV
{
  width:60px;
  margin:0 auto;
}

The margin value (0 auto) will align the inner DIV to center of the outer element. When I first met this requirement, it took me 3 hours to find out why the alignment is not working.

Floating DIV: Positioning

A very common problem developers face is positioning DIVs placed after another DIV which have the float property set. Lets have a look at the following senario:

 <div id="divImagesClose">Close</div>

 <span class="badge_list_resize" style="float: left;"
title="Wall Street">
   <img class="badge_list_image" src="images/wall_street.png" />
 </span>

 <div class="free">
 	<p>FREE</p>
 </div><br />

 <span class="badge_list_resize" style="float: left;"
title="Silver Tint">
   <img class="badge_list_image" src="images/silver_tint.png" />
 </span>

 <div class="free">
   <p>FREE</p>
 </div>

The CSS for this block is as follows:

#divImagesClose
{
 background:url(images/small-x.jpg) no-repeat 0px center;
 float:right;
 width:13px;
 height:12px;
 text-indent:-5000em;
 cursor:hand;
 cursor:pointer;
 margin:0 2px 5px;
}

.badge_list_resize
{
 width: 687px;
 height: 71px;
 clear:both;
}

.badge_list_image
{
 width: 100%;
 height: 100%;
}

The provided HTML block shows perfectly as expected in Firefox. But in Internet Explorer, you’ll find it not working correctly. Even though “badge_list_resize” class holds clear to be set as “both”, the position of the 1st span will not apply the clear as it should. As the DIV with float set to right has a smaller width than the element placed below it with clear value to right, the span on the left doesn’t apply the clear value in Internet Explorer. To resolve this, placing multiple wider elements below a floated element, they need to be wrapped within another DIV for which is clear is set to right as follows:

 <div id="divImagesClose">Close</div>

 <div style="clear:right">
   <span class="badge_list_resize" style="float: left;"
title="Wall Street">
     <img class="badge_list_image" src="images/wall_street.png">
   </span>
   <div class="free">
     <p>FREE</p>
   </div><br/>
   <span class="badge_list_resize" style="float: left;"
title="Silver Tint">
     <img class="badge_list_image" src="images/silver_tint.png">
   </span>
   <div class="free">
     <p>FREE</p>
   </div>
 </div>

Web 2.0 UI tweaks & tricks

In recent days, the trend of AJAX & service oriented services are quite in hype. For example, we can consider the start pages, such as Pageflakes, Netvibes, iGoogle and many more. The practice here is to organize your stuffs in a single page. For instance, if you are organizing your mails, local news, local weather, podcasts, videos and many more in a single page, the things will definitely gain quite a weight. The contents here are to be downloaded any way, but what about the presentation & interface? When you are serving this much of a load, you definitely need some tweaks on the interface & CSS. The highlights here are some tweaks for these scenarios. Even if you are going for a general web solution presenting good amount of content, these can go with them also. So hang on.

Optimizing Definitions

When defining the CSS styles, optimizations are required. Bytes can be reduced while you are writing the CSS if you just apply some trick. Design your system with hierarchical CSS definition. Avoid defining the same properties multiple times. Also try to combine multiple property values together.

For example, check out the following:

.radioItem { padding:2px 0 8px 5px; width:500px; }
.radioItemActive{ padding:2px 0 8px 5px; width:500px; color:#CDCDCD }

Both the classes have almost the same definition, except for the class radio_item_active has an additional color property defined. Here the definition should be as follows:

.radioItem, .radioItemActive{ padding:2px 0 8px 5px;width:500px; }
.radioItemActive{ color:#CDCDCD }

When you are defining different values for some properties like padding/margin (top, right, bottom and left), background (color, URL, repeat, left, top), border (size, color, type), it is better combining the values instead of declaring separately.

This reduces some bytes from loading. When dealing with large size CSS, these little bytes might sum up in quite some amount of bandwidth.

Reduced Use of Image

Whenever possible, avoid using images. When you have the interface designed by a designer, the design template received is mostly with images. For each image, a file request is made & retrieval of the image file takes the users valuable bandwidth. So try doing as many things as possible via CSS. Suppose you have a page header which has a logo & some background graphics. If it is possible to have the background graphics as a repeated image, instead of using the whole header as image, only the logo can be used as image & the background can be done through CSS as follows:

<div id=”header” style=”background: url(‘images/headerBg.gif’) repeat-x; padding: 12px 0 0 20px; height: 75px;”><img id=”logo” src=”images/logo.gif” alt=”The Logo” /></div>

Here the logo is placed as a gif file ‘logo.gif’ with 12 pixel padding from top & 20 pixel padding from left. The smallest unit for repetition is placed as ‘headerBg.gif’ in background & used as repeating on in the x-axis through the header div. It might come in mind that why not including the padding from top & left with in the logo image. If there’s any event to be hooked with the logo later, like some mouse click events, the mouse operation will be active in the unwanted padding place also. So it’s a good practice using the minimal size of image.

Image/CSS Spriting

If you are used to in working with CSS for a while & playing with the DIV’s properties, you might be familiar with the image spriting or CSS spriting. The concept here is practically compacting multiple images into a single file. The question that should come to knock in your mind that why making larger size files, as images are usually large files & compacting multiple will result in a larger output, when the bandwidth of the user is so much of a concern. The catch here is for fetching each file from the web, there are some overhead. And when user interactions are there to change the displayed interface, it might make the user see things blank for a while when the images to be shown are loading after the users operation, say a mouse over on an element. In these scenarios, spriting gives a better user experience. Moreover fetching less number of files will definitely decrease load time.

For spriting, DIVs are the better choice to implement. The following classes show the implementation.

.welcomeCheck {background: url(‘images/welcomeCheck.png’) no-repeat 0% 0%; height: 82px; width: 70px;}
.welcomeUncheck {background: url(‘images/welcomeCheck.png’) no-repeat -80px 0%; height: 82px; width: 70px;}

Here it represents the check & uncheck state of some options represented by image files. When unchecked, the ‘welcomeUncheck’ class is set. On user operation, the ‘welcomeCheck’ class is set changed from the previous. Here both the states are combined in the same image file side by side. Check out the last 2 values for the background property. The value 0% indicates no padding from the left of the image position & -80px indicates to move the image 80 pixels to the negative side of the x-axis, which results in showing the portion of the image hidden in the previous class. If the spriting is done in y-axis, the last value for the background property is used for measurement.

Image Transparency

Using transparent image can arise some problems in a web 2.0 application. So far we are familiar with the transparent GIF files. The key capability of GIF is compatibility with all browsers. But GIF has a big drawback, not supporting alpha transparency. In recent day designs, using alpha transparent images is quite a common practice. This feature comes in hand with the support of PNG files. Why is it still a problem? The issue here is browser support. PNG transparency is not supported in Internet Explorer prior to version 7. As many of the internet users are still using IE 6, the use of alpha transparency still stays as a problem. To overcome this, DirectX image transformation filters are used. Let’s have a look at the following definition example for IE 6:

#pageHeader {background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader (src=”images/header.png”, sizingMethod=”crop”);}

This will work same as the following definition:

#pageHeader {background: transparent url(’ images/header.png ‘) repeat-x; color: White; height: 24px;}

For scaling/plain transparency while filtering, ‘scale’ is used as the value for ‘sizingMethod’. When alpha transparency is needed, ‘crop’ is used instead.

Extreme XHTML

Whenever you are working on the HTML DOM objects, HTML is a must practice. XHTML, Extensible HyperText Markup Language, practically has the same depth of expression as HTML and conforms to XML syntax. Being a well formed XML document, XHTML can be handled easily through DOM programming. When you are working with the DOM & modifying the DOM, there are several things to keep in mind. In JavaScript, if performance is of extreme preference, it is better to use string operations, instead of DOM operations. The following example enlightens some on this issue. Another key feature of XHTML is cross browser support. Standard XHTML is compliant with all well known browsers including versions of Internet Explorer, Mozilla Firefox & Safari in Mac.

Let’s suppose there’s a blank div element with ID ‘records’. To insert another div with ID ‘newRecord’, the following can be done:

var records = document. getElementById(‘records’);
var newRecord = document.createElement(‘div’);
newRecord.id = ‘newRecord’;
records. appendChild(newRecord);

The greatest plus in using this type of DOM operation is it ensures the XHTML compliance. DOM operation always keeps the HTML well formed. But if there’s a large number of operations like this are to be done, then this much operation on DOM will make the system quite heavy, especially in IE6. IE6 have some weakness in handling large amount of DOM operations. To overcome these types of scenario, plain string operations come in the rescue. The previous block can be re-written with string operation as follows:

var records = document. getElementById(‘records’);
records.innerHTML = ‘<div id=” newRecord”></div>’;

There are still drawbacks in string operation. When you are doing things with string, it increases the performance, but also decreases control over the DOM object. If the DOM operation is performed, you’ll have control over the newly added DOM element. But when string operation is done, you’ll not have the DOM object in hand to manipulate. So it’s up to you when to choose what method according to your need.