Hover and Click Trigger For CIRCULAR Elements With jQuery

Today we want to share one possible solution to the circle hovering problem. We’ll create a plugin that will take care of the ‘mouseenter’, ‘mouseleave’ and ‘click’ events to be triggered only on the circular shape of the element and not its bounding box.

Applying a :hover pseudo-class to an element is widely known as the classic “hovering” over an element on a web page. A problem that arose with the introduction of the border-radius property is the non-realistic triggering of the hover event when entering the bounding box of the element and not just the actual visible area. This becomes extreme when we create a circle by setting the border-radius of a square to 50% (half of its outer width and height).

Today we want to share one possible solution to the circle hovering problem. We’ll create a plugin that will take care of the ‘mouseenter’, ‘mouseleave’ and ‘click’ events to be triggered only on the circular shape of the element and not its bounding box.



In our example, we’ll be creating a circle with some kind of hover effect. The structure will simply be:

<a href="#" id="circle" class="ec-circle">

And the style will be the following:

    width: 420px;
    height: 420px;
    -webkit-border-radius: 210px;
    -moz-border-radius: 210px;
    border-radius: 50%;
    text-align: center;
    overflow: hidden;
    font-family:'Kelly Slab', Georgia, serif;
    background: #dda994 url(HoverClickTriggerCircle.jpg) no-repeat center center;
        inset 0 0 1px 230px rgba(0,0,0,0.6),
        inset 0 0 0 7px #d5ad94;
    transition: box-shadow 400ms ease-in-out;
    display: block;
    outline: none;

Now, we will define a class for the hover effect but not a dynamic pseudo-class :hover. The idea is to apply this class then with jQuery when we enter the circular area of our element:

        inset 0 0 0 0 rgba(0,0,0,0.6),
        inset 0 0 0 20px #c18167,
        0 0 10px rgba(0,0,0,0.3);

Only when we have JavaScript disabled, we’ll add the pseudo-class. This style can be found in the noscript.css:

        inset 0 0 0 0 rgba(0,0,0,0.6),
        inset 0 0 0 20px #c18167,
        0 0 10px rgba(0,0,0,0.3);


We are going to create a simple plugin that basically “redefines” the three events mentioned earlier. We’ll make the events only applicable on the circular shape:

$.CircleEventManager            = function( options, element ) {
    this.$el = $( element );
    this._init( options );

$.CircleEventManager.defaults   = {
    onMouseEnter    : function() { return false },
    onMouseLeave    : function() { return false },
    onClick         : function() { return false }

$.CircleEventManager.prototype  = {
    _init           : function( options ) {
        this.options = $.extend( true, {}, $.CircleEventManager.defaults, options );
        // set the default cursor on the element
        this.$el.css( 'cursor', 'default' );

    _initEvents     : function() {
       var _self   = this;
           'mouseenter.circlemouse'    : function( event ) {
               var el  = $(event.target),
               circleWidth   = el.outerWidth( true ),
               circleHeight  = el.outerHeight( true ),
               circleLeft    = el.offset().left,
               circleTop     = el.offset().top,
               circlePos     = {
                       x     : circleLeft + circleWidth / 2,
                       y     : circleTop + circleHeight / 2,
                       radius: circleWidth / 2

                // save cursor type
                var cursor  = 'default';
                if( _self.$el.css('cursor') === 'pointer' || _self.$el.is('a') )
                    cursor = 'pointer';
                el.data( 'cursor', cursor );
                el.on( 'mousemove.circlemouse', function( event ) {
                var distance    = Math.sqrt( Math.pow( event.pageX - circlePos.x, 2 ) + Math.pow( event.pageY - circlePos.y, 2 ) );

                if( !Modernizr.borderradius ) {

                  // inside element / circle
                  el.css( 'cursor', el.data('cursor') ).data( 'inside', true );
                  _self.options.onMouseEnter( _self.$el );

                 else {

                   if( distance <= circlePos.radius && !el.data('inside') ) {                       // inside element / circle                       el.css( 'cursor', el.data('cursor') ).data( 'inside', true );                       _self.options.onMouseEnter( _self.$el );                                                   }                     else if( distance > circlePos.radius && el.data('inside') ) {

                      // inside element / outside circle
                      el.css( 'cursor', 'default' ).data( 'inside', false );
                      _self.options.onMouseLeave( _self.$el );
            'mouseleave.circlemouse'    : function( event ) {
              var el  = $(event.target);
               if( el.data( 'inside' ) ) {
                  el.data( 'inside', false );
                  _self.options.onMouseLeave( _self.$el );
            'click.circlemouse'         : function( event ) {
              // allow the click only when inside the circle
                var el  = $(event.target);
                if( !el.data( 'inside' ) )
                    return false;
                    _self.options.onClick( _self.$el );
    destroy             : function() {     

When we enter with the mouse in the square bounding box of our circle, we bind the ‘mousemove’ event to the element and like that we can track if the distance of the mouse to the center of the element if longer than the radius. If it is, we know that we are not yet hovering the circular area of the element.

Once the distance of the mouse is shorter than the radius, we know that we entered the circle and we trigger our custom ‘mouseenter’ event.
We also only allow the click event when the mouse is inside of the circle.
In our example we will then apply our plugin to the regarding element. In our case, we are adding the hover class on ‘mouseenter’ and removing it on ‘mouseleave’.

    onMouseEnter    : function( el ) {


    onMouseLeave    : function( el ) {


    onClick         : function( el ) {



Remember that the “normal” pseudo hover class is also defined in the noscript.css which gets applied when JavaScript is disabled.

view demo

Your turn

I hope you enjoyed this article and the techniques I used. Please share your comments and questions below!

Posted by: Dhiraj kumar

Random 3D Explosions, 3D clouds – Effects with CSS 3D and jQuery


This tutorial will try to guide you through the steps to create a 3D-like, explosions in sky or billboard-based clouds. There are a few advanced topics, mainly how 3D transformations via CSS properties work. If you want to find more information, this is a nice place to begin.

If you’re in a hurry, just check the final result.


The tutorial is divided into sections, each with a different step to understand and follow the process, with HTML, CSS and Javascript blocks. Each step is based on the previous one, and has a link to test the code. The code in the tutorial is a simplified version of the demos, but the main differences are documented on every section.


First, we need two div elements: viewport and world. All the rest of the elements will be dynamically created.

Viewport covers the whole screen and acts as the camera plane. Since in CSS 3D Transforms there is no camera per se, think of it as a static sheet of glass through which you see a world that changes orientation relative to you. We’ll position all our world objects (or scene) inside it, and that’s what will be transformed around.

World is a div that we are going to use to anchor all our 3D elements. Transforming (rotating, translating or scaling) world will transform all our elements. For brevity and from here on, I’m using non-prefixed CSS properties. Use the vendor prefix (-webkit, -moz, -o, -ms, etc.) where appropriate.

This is all the markup we’ll need:

<div id="viewport">
    <div id="world"></div>


These next are our two CSS definitions. It’s very important to center the div that contains our scene (world in our case) in the viewport, or the scene will be rendered with an offset! Remember that you are still rotating an element that is positioned inside the document, exactly like any other 2D element.

#viewport {
	-webkit-perspective: 1000; -moz-perspective: 1000; -o-perspective: 1000; 
	position: absolute; 
	left: 0; 
	top: 0; 
	right: 0; 
	bottom: 0; 
	overflow: hidden;
	background-image: linear-gradient(bottom, rgb(69,132,180) 28%, rgb(31,71,120) 64%);
	background-image: -o-linear-gradient(bottom, rgb(69,132,180) 28%, rgb(31,71,120) 64%);
	background-image: -moz-linear-gradient(bottom, rgb(69,132,180) 28%, rgb(31,71,120) 64%);
	background-image: -webkit-linear-gradient(bottom, rgb(69,132,180) 28%, rgb(31,71,120) 64%);
	background-image: -ms-linear-gradient(bottom, rgb(69,132,180) 28%, rgb(31,71,120) 64%);
	background-image: -webkit-gradient(
			left bottom,
			left top,
			color-stop(0.28, rgb(69,132,180)),
			color-stop(0.64, rgb(31,71,120))

#world {
	position: absolute; 
	left: 50%; 
	top: 50%; 
	margin-left: -256px; 
	margin-top: -256px; 
	height: 512px; 
	width: 512px; 
	-webkit-transform-style: preserve-3d; 
	-moz-transform-style: preserve-3d; 
	-o-transform-style: preserve-3d; 
	pointer-events: none;

CSS For Adding Clouds Base

Now we start adding real 3D content. We add some new div which are positioned in the space, relatively to world. It’s esentially adding several absolute-positioned div as children of world, but using translate in 3 dimensions instead of left and top. They are centered in the middle of world by default. The width and height don’t really matter, since these new elements are containers for the actual cloud layers. For commodity, it’s better to center them (by setting margin-left and margin-top to negative half of width and height).

.cloudBase {
		position: absolute; 
		left: 256px; 
		top: 256px; 
		width: 20px; 
		height: 20px; 
		margin-left: -10px; 
		margin-top: -10px

CSS for Clouds Layer

Now things start getting interesting. We add several absolute-positioned .cloudLayer div elements to each .cloudBase. These will hold our cloud textures.

.cloudLayer {
		position: absolute; 
		left: 50%; 
		top: 50%; 
		width: 256px; 
		height: 256px; 
		margin-left: -128px; 
		margin-top: -128px; 
		-webkit-transition: opacity .5s ease-out; 
		-moz-transition: opacity .5s ease-out; 
		-o-transition: opacity .5s ease-out;

jQuery (JavaScript)

We add generate() and createCloud() functions to populate world. Note that random_{var} are not real variables but placeholder names for the real code, which should return a random number between the specified range.

var layers = [],
	objects = [],
	textures = [],

	world = document.getElementById( 'world' ),
	viewport = document.getElementById( 'viewport' ),

	d = 0,
	p = 400,
	worldXAngle = 0,
	worldYAngle = 0,
	computedWeights = [];

	viewport.style.webkitPerspective = p;
	viewport.style.MozPerspective = p;
	viewport.style.oPerspective = p;
	textures = [
		{ name: 'white cloud', 	file: 'cloud.png'	, opacity: 1, weight: 0 },
		{ name: 'dark cloud', 	file: 'darkCloud.png'	, opacity: 1, weight: 0 },
		{ name: 'smoke cloud', 	file: 'smoke.png'	, opacity: 1, weight: 0 },
		{ name: 'explosion', 	file: 'explosion.png'	, opacity: 1, weight: 0 },
		{ name: 'explosion 2', 	file: 'explosion2.png'	, opacity: 1, weight: 0 },
		{ name: 'box', 		file: 'box.png'		, opacity: 1, weight: 0 }

	function setTextureUsage( id, mode ) {
		var modes = [ 'None', 'Few', 'Normal', 'Lot' ];
		var weights = { 'None': 0, 'Few': .3, 'Normal': .7, 'Lot': 1 };
		for( var j = 0; j < modes.length; j++ ) {
			var el = document.getElementById( 'btn' + modes[ j ] + id );
			el.className = el.className.replace( ' active', '' );
			if( modes[ j ] == mode ) {
				el.className += ' active';
				textures[ id ].weight = weights[ mode ];
	setTextureUsage( 0, 'Few' );
	setTextureUsage( 1, 'Few' );
	setTextureUsage( 2, 'Normal' );
	setTextureUsage( 3, 'Lot' );
	setTextureUsage( 4, 'Lot' );


	function createCloud() {

		var div = document.createElement( 'div'  );
		div.className = 'cloudBase';
		var x = 256 - ( Math.random() * 512 );
		var y = 256 - ( Math.random() * 512 );
		var z = 256 - ( Math.random() * 512 );
		var t = 'translateX( ' + x + 'px ) translateY( ' + y + 'px ) translateZ( ' + z + 'px )';
		div.style.webkitTransform = t;
		div.style.MozTransform = t;
		div.style.oTransform = t;
		world.appendChild( div );

		for( var j = 0; j < 5 + Math.round( Math.random() * 10 ); j++ ) {
			var cloud = document.createElement( 'img' );
			cloud.style.opacity = 0;
			var r = Math.random();
			var src = 'troll.png';
			for( var k = 0; k < computedWeights.length; k++ ) { 
				if( r >= computedWeights[ k ].min && r <= computedWeights[ k ].max ) { 					
( function( img ) { img.addEventListener( 'load', function() {
 						img.style.opacity = .8;
					} ) } )( cloud );
 					src = computedWeights[ k ].src; 
cloud.setAttribute( 'src', src ); 
cloud.className = 'cloudLayer'; 		 			
var x = 256 - ( Math.random() * 512 ); 
var y = 256 - ( Math.random() * 512 ); 
var z = 100 - ( Math.random() * 200 ); 
var a = Math.random() * 360; 
var s = .25 + Math.random(); 
x *= .2; y *= .2; 
cloud.data = {x: x, y: y, z: z, a: a, s: s, speed: .1 * Math.random()}; 
var t = 'translateX( ' + x + 'px ) translateY( ' + y + 'px ) translateZ( ' + z + 'px ) rotateZ( ' + a + 'deg ) scale( ' + s + ' )'; 
cloud.style.webkitTransform = t; 
cloud.style.MozTransform = t; 			
cloud.style.oTransform = t; 			
div.appendChild( cloud ); 			
layers.push( cloud ); 		} 		 		
return div; 	 	
function generate() { 		
objects = []; 		
if ( world.hasChildNodes() ) { 			
while ( world.childNodes.length >= 1 ) {
				world.removeChild( world.firstChild );       
		computedWeights = [];
		var total = 0;
		for( var j = 0; j < textures.length; j++ ) { 			
if( textures[ j ].weight > 0 ) {
				total += textures[ j ].weight;
		var accum = 0;
		for( var j = 0; j < textures.length; j++ ) { 			
if( textures[ j ].weight > 0 ) {
				var w = textures[ j ].weight / total;
				computedWeights.push( {
					src: textures[ j ].file,
					min: accum,
					max: accum + w
				} );
				accum += w;
		for( var j = 0; j < 5; j++ ) {
			objects.push( createCloud() );


For the final effect, we fill cloudLayer div for an img with a cloud texture. The textures should be PNG with alpha channel to get the effect right.



Of course, you can use any texture or set of textures you want: smoke puffs, plasma clouds, green leaves, flying toasters… Just change the background-image that a specific kind of cloud layer uses. Mixing different textures in different proportions gives interesting results.

Adding elements in random order is fine, but you can also create ordered structures, like trees, duck-shaped clouds or complex explosions. Try following a 3D curve and create solid trails of clouds. Create a multiplayer game to guess the shape of a 3D cloud. The possibilities are endless!

I hope it’s been an interesting tutorial and not too hard to follow.

view demo

I hope you like the result and don’t hesitate to share your thoughts about it. Thanks for reading!

Posted by: Dhiraj kumar

Hot Tea / Coffee with Animated Smoke Effect – jQuery & CSS

This effect has been created with some cool jQuery animation effect. For Smoke effect I have used a png transparent image. I have already updated this for IE too. As we already know transparency of png creates some bad side-effects on IE (png transparency bugs in IE). You can check the demo code and see how it’s done. Basically, the Javascript function creates some div with smoke background in random positions.  so, the effect looks more random even though it’s totally deterministic. Each smoke moves in the Y axis with a linear function and fade with a cosine function. Pretty simple effect, but effective.



#viewport {
position: relative;
width: 800px;
height: 600px;
overflow: hidden;
background:url('images/milk_tea.jpg') 0 0 no-repeat
#viewport .smoke {
position: absolute;
width: 250px;
height: 250px;
background:url('images/smoke-texture.png') no-repeat;
bottom: 150px;

The jQuery

Now, We are including jquery library and the easing plugin for creating this affect realistic.

<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script src="http://demo.web3designs.com/jquery-easing.min.js"></script>
<script type="text/javascript">
$(function () {
    if (!$.browser.msie) {
        var a = 0;
        for (; a < 15; a += 1) {
            setTimeout(function b() {
                var a = Math.random() * 1e3 + 5e3,
                    c = $("
", {
                        "class": "smoke",
                        css: {
                            opacity: 0,
                            left: Math.random() * 200 + 80
                    opacity: 1
                }, {
                    duration: a / 4,
                    easing: "linear",
                    queue: false,
                    complete: function () {
                            opacity: 0
                        }, {
                            duration: a / 3,
                            easing: "linear",
                            queue: false
                }), $(c).animate({
                    bottom: $("#viewport").height()
                }, {
                    duration: a,
                    easing: "linear",
                    queue: false
                })).then(function () {
            }, Math.random() * 3e3)
    } else {
        "use strict";
        var a = 0;
        for (; a < 15; a += 1) {
            setTimeout(function b() {
                var a = Math.random() * 1e3 + 5e3,
                    c = $("
", {
                        "class": "smoke",
                        css: {
                            left: Math.random() * 200 + 80
                $.when($(c).animate({}, {
                    duration: a / 4,
                    easing: "linear",
                    queue: false,
                    complete: function () {
                        $(c).animate({}, {
                            duration: a / 3,
                            easing: "linear",
                            queue: false
                }), $(c).animate({
                    bottom: $("#viewport").height()
                }, {
                    duration: a,
                    easing: "linear",
                    queue: false
                })).then(function () {
            }, Math.random() * 3e3)

view demo


I’ve done some changes in my jquery script and fix IE png transparency bug.

Thanks for reading and looking forward to read your thoughts!

Posted by: Dhiraj kumar

Cool Animated Fire Effects with CSS3 and jQuery

This effect has been created with some jQuery for setting different CSS3 text-shadow’s in a div. You can check the demo code to see how it’s done. Basically, the Javascript function creates 3 text-shadows (white, yellow and red) with coprime “cycle durations” so the effect looks more random even though it’s totally deterministic.


Each shadow moves in the Y axis with a linear function and in the X axis with a cosine function. Pretty simple, but effective.


      font-size: 42px;
      font-weight: bold;
      text-align: center;

The jQuery

<script type="text/javascript">
var step = 1;
function nextShadow(){
	$('#onfire span').each(function(){
	    y = parseFloat($(this).attr("y_pos"));
	    y += step + Math.random()*3;
	    $(this).attr("y_pos", y);
	    shaking = Math.random();
	    shadow1 = "0px 0px "+(y%5)+"px white";
	    shadow2 = shaking*24/y*Math.cos(y/5)*15+"px -"+(shaking*4/y+(y%17))+"px "+(shaking+(y%17))+"px red";
	    shadow3 = shaking*24/y*Math.cos(y/7)*15+"px -"+(shaking*4/y+(y%31))+"px "+(shaking+(y%31))+"px #993";
	    shadow4 = shaking*24/y*Math.cos(y/13)*15+"px -"+(shaking*4/y+(y%41))+"px "+(shaking+(y%41))+"px yellow";
	    $(this).css("text-shadow", shadow2+", "+shadow1+", "+shadow4+", "+shadow3);
    $('#onfire span').each(function(){$(this).attr("y_pos","0");});
   setInterval(nextShadow, 50); 

view demo


I’ve added some randomisation to the algorithm, as well as an individual animation to each of the letters (which, as a drawback, makes the effect run less smooth). I’ve also added a fourth shadow in dark yellow. You can freely use the code by keeping the mention to this site on it.

Thanks for reading and looking forward to read your thoughts!

Posted by: Dhiraj kumar

Animated Notification bubble icon with CSS3 keyframe animation

The other day, while working on a web project, I had to emphasize somehow a dynamic notification bubble. Basically, every time the notification value changes, a visual effect was needed in order to get user’s attention. So I made that using CSS3 keyframe animation.



For this example, we’ll borrow the markup structure and look from my CSS3 dropdown menu.

    <li><a href="">Dashboard</a></li>
    <li><a href="">Friends</a></li>
    	<a href="">Message
    <li><a href="">Games</a></li>
    <li><a href="">Settings</a></li>

The focus will be on the <span>, which is the notification bubble that will be animated.


The .animating class represents an CSS3 animation that uses a bezier curve.

	animation: animate 1s cubic-bezier(0,1,1,0);			

@keyframes animate{
	from {
	   transform: scale(1);
	to {
	   transform: scale(1.7);

The jQuery

It’s not as easy as you might think to restart an animation and Chris Coyier wrote a good article about it.

The method I chose for this example involves using JavaScript’s setTimeout() method. So, every time the notification value changes, the .animating class is removed after a second (exactly how long the proper animation lasts).

In production, you will not need the counterValue variable. This is used just for our working example in order to be able to increment and decrement the notification value.

var counterValue = parseInt($('.bubble').html()); // Get the current bubble value

function removeAnimation(){
	setTimeout(function() {
	}, 1000);			

	counterValue--; // decrement
	$('.bubble').html(counterValue).addClass('animating'); // animate it
	removeAnimation(); // remove CSS animating class

	counterValue++; // increment
	$('.bubble').html(counterValue).addClass('animating'); // animate it
        removeAnimation(); // remove CSS animating class

view demo

Simple, but effective

I think this is a simple and practical example on how to use a CSS3 animation to enhance user experience. Further, you can experiment with the bezier curve values and come up with some other cool effects.

Thanks for reading and looking forward to read your thoughts!

Posted by: Dhiraj kumar

Image Sprites – How to merge multiple images, and how to split them

An Image Sprites is a single image which is merged with multiple images. The reason why Image Sprites are needed instead of inserting multiple images into a page is to SAVE network bandwidth as well as reduce the number of server requests. Since inserting many images into a page will take longer time to load the pages, merging images into a single will help reduce loading time. For these reasons, I would recommend to use “CSS Image Sprites” function instead of inserting multiple images. Unfortunately, most of designers/developers not support this function as default, but through this tutorial, you would be able to merge multiple images into a single image as well as manipulating CSS.

“Image Sprites” is strongly recommended for Web, because Web themes have many graphics as default. Therefore, reducing the number of images is necessary to let people as well as search engines visit your sites faster than before. Some times ago, I have already posted an example of a cartoon type animation with help of Image Sprites.

Let me give you an example for easier understandings. Here is lots of avatars I have to put into a page. Without Image Sprites, I have to insert 24 individual avatars into a page. It will generate 24 requests of your web server so that it will take a long time to load.

24 image files to load / 24 requests

Just 1 image file to load / 1 request

With using “Image Sprites”, Only one request and one loading time will be generated. Which one do you think better?

In addition, with the help of “Image Sprites”, you can make use of hover effect more easily. In this tutorial, I will describe how to use Image Sprites with hover effects (View Demo).

To get started (Preparation)

  1. You may need to prepare more than two same size images to be inserted into a page like the avatar image file above.
  2. For this tutorial, I will use these 6 images below as an example. All six buttons’ sizes are equal as 33×33.

3 left images will be used for normal links, and the rest of images will be used for hover effects.

This single image below will be used for “Image Sprites”.


  1. Download .zip file or View Demo.
  2. Extract the compressed file onto your hard drive.
  3. Open “imagesprites.html” file using any TextEditor (Notepad/Dreamweaver).
  4. I will let you know some parts you need to replace so that you better modify some codes using text editor.
  5. This code is for this example so that your code will be different. You can refer to this code about how it works.
  6. Take a look at this part of the source code below:
.prev-button {
    width: 33px; height: 33px; border: 0px; background:url('/images/controllers.png') 0 0
a:hover .prev-button {
    width: 33px; height: 33px; border: 0px; background: url('/images/controllers.png') 0px -33px
.play-button  {
    width: 33px; height: 33px; border: 0px; background:url('/images/controllers.png') -33px 0
a:hover .play-button  {
    width: 33px; height: 33px; border: 0px; background: url('/images/controllers.png') -33px -33px
.next-button  {
    width: 33px; height: 33px; border: 0px; background:url('/images/controllers.png') -66px 0
a:hover .next-button  {
    width: 33px; height: 33px; border: 0px; background: url('/images/controllers.png') -66px -33px
image sprite
 As you can see, the first image’s position is “0 0” (.prev-button). The second image (.play-button) position is “-33px 0”. Because each width is set to 33px. Hence, the next image’s position should be “-66px 0”. On the other hand, for hover images, their Y position should be “-33px”, because each height is set to 33px.
  1. If you have set all, the next is to insert HTML codes for each image class like below:
<body style="background: transparent; margin: 0pt; ">
<a href="URL" target="_top"><img class="prev-button" src="/images/spacer.gif" /></a>

<a href="URL" target="_top"><img class="play-button" src="/images/spacer.gif" /></a>

<a href="URL" target="_top"><img class="next-button" src="/images/spacer.gif" /></a>
  1. If you don’t want an image to be linked, remove href= “URL” target= “_top” tag.
  2. Replace class names such as “prev-button”, “play-button”, and “next-button” to yours.
  3. Make sure the classes doesn’t have “.” at the very front.
  4. Modifying codes is done. You can apply this technique to other merged images.
  5. Make sure “spacer.gif” as well as your merged image file are also uploaded to the right place such as “/images/”.
  6. You are ready to check how “Image Sprites” works correctly. You will reduce the number of server requests as well as save network bandwidth with this CSS technique.

Posted by: Dhiraj kumar

CSS tricks and hacks – Latest top ten useful tips

CSS can be complex, and as each new browser version is released, you may well find yourself struggling to keep up with the latest tips and hacks. But those tips and hacks will save your sanity! Here, I’ve put together the ten tips that I find most helpful, to save you the hassle of scrounging around the Web for solutions when time is tight.


Nearly all HTML elements are either block or inline elements. The characteristics of block elements include:

  • Always begin on a new line
  • Height, line-height and top and bottom margins can be manipulated
  • Width defaults to 100% of their containing element, unless a width is specified

Examples of block elements include <div><p><h1><form><ul> and <li>. The characteristics of inline elements, on the other hand, are the opposite of block elements:

  • Begin on the same line
  • Height, line-height and top and bottom margins can’t be changed
  • Width is as long as the text/image and can’t be manipulated

Examples of inline elements include <span><a><label><input><img><strong> and <em>.

To change an element’s status, you can use display: inline or display: block. But what’s the point of changing an element from being block to inline, or vice-versa? Well, at first it may seem like you might hardly ever use this trick, but in actual fact, this is a very powerful technique, which you can use whenever you want to:

  • Have an inline element start on a new line
  • Have a block element start on the same line
  • Control the width of an inline element (particularly useful for navigation links)
  • Manipulate the height of an inline element
  • Set a background colour as wide as the text for block elements, without having to specify a width

The box model hack  is used to fix a rendering problem in pre-IE 6 browsers on PC, whereby the border and padding are included in, rather than added onto, the width of an element. A number of CSS-based solutions have been put forward to remedy this; here’s another one that I really like:

padding: 2em;
border: 1em solid green;
width: 20em;
width/**/:/**/ 14em;

The first width command is read by all browsers; the second by all browsers except IE5.x on PC. Because the second command comes second, it takes precedence over the first: any command that comes second will always override a preceding command. So, how does all this work?

By placing empty comment tags (/**/) before the colons, we instruct IE5.0 to ignore the command. Likewise, if we place empty comment tags after the colon, IE5.5 will ignore the command. Using these two rules in conjunction with each other, we can hide the command from all of IE5.x browsers.


A very handy CSS command that exists is the min-width command, whereby you can specify a minimum width for any element. This can be particularly useful for specifying a minimum width for a page.

Unfortunately, IE doesn’t understand this command, so we’ll need to come up with a new way of making this functionality work in this browser. First, we’ll insert a <div> under the <body> tag, as we can’t assign a minimum width to the <body>:

<div class="container">

Next, we create our CSS commands, to create a minimum width of 600px:

#container   {
min-width: 600px;
width:expression(document.body.clientWidth < 600? "600px": "auto" );

The first command is the regular minimum width command; the second is a short JavaScript command that only IE understands. Do note, though, that this command will cause your CSS document to become invalid; you may prefer to insert it into the head of each HTML document to get around this.

You might also want to combine this minimum width with a maximum width:

#container {
min-width: 600px;
max-width: 1200px;
width:expression(document.body.clientWidth < 600? "600px" : document.body.clientWidth > 1200? "1200px" : "auto");

IE has a rather strange way of doing things. It doesn’t understand the min-width and min-height commands, but instead interprets width and height as min-width and min-height — go figure!

This can cause problems, because we may need boxes to be resizable should we need to fit more text into them, or should the user resize the text. If we use only the width and height commands on a box, non-IE browsers won’t allow the box to resize. If we only use the min-width and min-height commands, though, we can’t control the width or height in IE!

This can be especially problematic when using background images. If you’re using a background image that’s 80px wide and 35px high, you’ll want to make sure that the default size for a box using this image is exactly 80 x 35px. However, if users resize the text, the box size will need to expand gracefully.

To resolve this problem, you can use the following code for a box with class="box":

.box {
width: 80px;
height: 35px;

html>body .box {
width: auto;
height: auto;
min-width: 80px;
min-height: 35px;

All browsers will read through the first CSS rule, but IE will ignore the second rule because it makes use of the child selector command . Non-IE browsers will read through the second one, which will override the values from the first rule, because this CSS rule is more specific, and CSS rules that are more specific always override those that are less specific.


One of the lesser known, but really useful CSS commands is the text-transform command. Three of the more common values for this rule are:  text-transform: uppercasetext-transform: lowercase and text-transform: capitalize.  The first rule turns all characters into capital letters, the second turns them all into small letters, and the third makes the first letter of each word a capital letter.

This command is incredibly useful to help ensure consistency in style across an entire Website,  particularly if it has a number of content editors. Say for example your style guide dictates that words in headings must always begin with capital letters.  To ensure that this is always the case, use text-transform: capitalize. Even if site editors forget about the capitalisation, their mistake won’t show up on the Website.

It’s also preferable to use text-transform:  uppercase to capitalise words, as screen readers may pronounce shorter words in capital letters as acronyms. A great example of this is ‘CONTACT US’, which is pronounced as ‘contact U S’ by some screen readers.


IE exhibits a very strange bug whereby text or background images sometimes disappear from sight. These items are still actually present and, if you highlight everything on screen or hit refresh, they’ll often re-appear. Kind of strange, huh?

This problem mostly occurs on background images and on text positioned next to a floated element. To remedy the problem,  simply insert position: relative into the CSS command for the disappearing element, and for some bizarre reason, that’ll usually fix the problem. If this doesn’t work (and sometimes, it doesn’t), assign a width to the offending element in the CSS — that should fix the problem.


Sometimes, you may actually want to make text invisible. Invisible text can be especially useful for screen reader users, perhaps to assign a label to a form item, or insert a heading ahead of a section. Don’t want to change the visual appearance by inserting these elements? Make them invisible, and no one using a visual browser will know they’re there.

You may also want to make text invisible if using a print or handheld CSS file, as some information may not need to be displayed on either of these mediums (see below for more on this).

To make text invisible, you can use display: none — easy! This works fine for hiding text from handhelds (if  CSS is supported) and printed Web pages, but isn’t so great for many screen readers.  Screen readers are now becoming too clever for their own good, and some will actually ignore any text that has the rule display: none assigned to it.

Therefore, for screen readers users, a new approach is needed: position: absolute; left: -9000px.  This basically takes the text and positions it 9000px to the left of the left edge of the screen, essentially making it invisible.


A separate CSS document can be created for PDAs and mobile phones, and activated only when one of these devices is being used to access your site. More and more Websites are creating separate CSS documents for printing , so Web pages automatically become print-friendly when users choose to print them. You can do the same for handheld devices.

The following command is used to call up the CSS document for handheld:

<link type="text/css" rel="stylesheet" href="handheldstyle.css" media="handheld" />

CSS commands in the handheld CSS file override any equivalent commands in the main CSS document.  So, what commands should you place in this file?
Ideally, you want users of handheld devices to avoid having to scroll horizontally.

To test this, open up your Website in a regular browser window and resize it to 150px in width. Then, open up your main CSS file and insert some new commands at the very bottom of the document. The commands you place here should adjust the layout of the Website so that it doesn’t require horizontal scrolling at a width of 150px. Then, open up a new document, cut and paste these new commands over, and save it as handheldstyle.css (or whatever name you want to give it).

Your Websites offering to users of handheld devices should be quite different to its offering to traditional Web browsers, as the user experience is quite different on a handheld device. For further information, a book such as Handheld Usability , by S.W. Weiss, is a great read.


Back in the early days of the Web, 3-d buttons that appeared to become pushed in when moused over were all the rage. At that time, this could only be achieved through images and JavaScript, but now, with the advent of CSS, we can go retro and re-create this 3-d effect.

The main CSS commands you’ll need are:

a {
display: block;
border: 1px solid;
border-color: #aaa #000 #000 #aaa;
width: 8em;
background: #fc0;

a:hover {
position: relative;
top: 1px;
left: 1px;
border-color: #000 #aaa #aaa #000;

Aside from these commands, you can insert other commands to achieve the desired presentation effect — the only limit is your imagination!


Most Websites highlight the navigation item relating to each user’s location within the Website, to help users orientate themselves. This is a fundamental requirement for basic usability, but it can be a pain: we need to tweak the HTML code behind the navigation for each and every page. Can we have the best of both worlds? Is it possible to have the navigation highlighted on every page, without having to tweak the HTML code on every page? Of course it is!

First of all, you’ll need to assign a class to each navigation item:

<li><a href="#" class="home">Home</a></li>
<li><a href="#" class="about">About us</a></li>
<li><a href="#" class="contact">Contact us</a></li>

You’ll then need to insert an id into the <body> tag. The id should be representative of where users are located in the site, and should change when users move to a different site section. When on the ‘Home’ page, it should read <body id="home">, in ‘About Us’, it should read <body id="about">, and in ‘Contact Us’, <body id="contact">.

Next, you create a new CSS rule:

#home .home, #about .about, #about .about, #contact .contact {
commands for highlighted navigation go here

This basically creates a rule that only takes effect when class="home" is contained within id="home", and when class="about" is in id="about" and class="contact" is in id="contact". These situations will only occur when the user is in the appropriate section of the site,  seamlessly creating our highlighted navigation item.

Posted by: Dhiraj kumar

Clearing floats methods nowadays

At my beginnings as a web designer using Div tags, when I first discovered clear floats I was so happy and it was for sure an “a-ha” moment. Since then, so many things have changed and new clearing methods have appeared. One thing remained the same: the need to clear floats.

In this article, we’ll see some effective solutions for clearing floated elements.


But first, what is float?

Arranging website page elements was always a struggle for you as a web designer. To achieve your desired website layout, a lot of calculation of box dimensions are needed, and various implementation decisions must be taken as well.

At the beginning, perhaps you used table elements to structure your layout, and even if tables are very intuitive, the table purpose is to list tabular data. You also tried the CSS display values like: tabletable-cell or table-row to build structures, but shortly you gave up as there wasn’t enough support for that.

In the end, you got rid of table markup and skipped to div floats.

So, float is a CSS property which help you aligning and positioning your web page elements.

Simple floats example

Clearing floats

Elements placed after a floated element will wrap around the floated element. To avoid this behavior, you must clear floats. To do that, generally you use the clear property which has four values: leftrightboth and none.

<div style="float:left"></div>
<div style="float:right"></div>
<div style="clear:both"></div>

The above is a common example.

Beside the above example that requires extra HTML markup, below is a list with some clearing methods that I found very useful (and they do not require extra markup):

Clearfix reloaded by Thierry Koblentz


  content: ".";
  display: block;
  height: 0;
  overflow: hidden;
.clearfix:after {clear: both;}
.clearfix {zoom: 1;} /* IE < 8 */

New clearfix hack by Jeff Starr


  visibility: hidden;
  display: block;
  font-size: 0;
  content: " ";
  clear: both;
  height: 0;

* html .clearfix             { zoom: 1; } /* IE6 */
*:first-child+html .clearfix { zoom: 1; } /* IE7 */

Micro clearfix hack by Nicolas Gallagher




/* For IE 6/7 (trigger hasLayout) */

CSS clearing floats with overflow by Nick La


That’s it!

You may already know the above techniques and my questions is:  Which one do you use most? Share your opinion with us!

Posted by: Dhiraj kumar

jQuery Plugin for Cartoon-like Background Image Sprite Animation – AniDG – (alernative to animated Gif)

What is AniDg?

AniDg is a simple plugin for jQuery which allows you animate background images. The plugin is basically an alternative to the animated GIF but with several benefits. At first, it’s always better to use an animated GIF as this format is supported by all browsers without any JavaScript code or additional markup, but the “dark side” of it is that an animated GIF allows only 256 colors and you cannot control animation in any way. The AniDg loads a long vertical image and changes its background position with the speed you setup, giving you more control of the animation. For Better quality you can call PNG, JPG, GIF images in background image sprite as per your requirements.


jQuery Plugin AniDG Background image animation


  1. Light-weight script (Only 1Kb :))
  2. Easy to integrate
  3. Fully customizable via CSS
  4. Works with all modern browsers 🙂

How to Use


Simply place the following code anywhere inside thetag of your webpage:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://demo.web3designs.com/jquery-ani.dg.min.js"></script>


STEP ONE: Download AniDg.zip or http://demo.web3designs.com/AniDg.zip. The package already contains all files used in this demo.

STEP TWO: Unzip and place the file jquery-ani.dg.min.js in the same location as the webpage that is displaying the animation. (Make sure paths to files are correct.)

STEP THREE: include the following code in the <head>…</head> section of your webpage:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="jquery-ani.dg.min.js"></script>

3.) Add a style containing the url to your background with animation (this may be added to a separate CSS document or inside the <head>…</head> tag):

<style type="text/css">
#animation-1 {
background: url(images/sample-animation.gif) no-repeat left top;

4.) Add an empty DIV which will display animation in your document:

<div id="animation-1"></div>

5.) Add the following code to your <head>…</head> tag to initialize AniDg and start the animation.

<script type="text/javascript">
$('#animation-1').anidg({ frameWidth: 100, frameHeight: 100, speed: 100, totalFrames: 19 });

That’s it 😉 Click the Demo button to see it in action.

Public Functions

Start playing animation.

Pause animation.

Stop animation.


The table below contains a list of parameters accepted by the .anidg() function.

Parameters Description
frameWidth Width of a single frame.
frameHeight Height of a single frame.
speed Animation speed.
totalFrames Total frames in the animation.
loop Loop an animation or not. By default, value is true.

Posted by: Dhiraj kumar

DG_Slider – An Ultimate jQuery Content Slider Plugin

DG_Slider is a jQuery  plugin that carries you on a content slider or carousel ride filled with images and HTML content. Put simply, you can navigate images and/or HTML in a carousel-style widget. It is light weight, at about 14 KB in size, yet very flexible and customizable to fit most of our needs. DG_Slider is a great plug-in. It offers a host of features and it is so customizable that you are limited only by your imagination.

DG_Slider : A ultimate jquery content slider plugin with multiple options


  • Horizontal, vertical, and fade transitions
  • Display and move multiple slides at once (carousel)
  • Prev / next, pager, auto controls
  • Start / Stop control
  • Easing transitions
  • Random start
  • Ticker mode also :)
  • Before, after, first, last, next, prev callback functions
  • Optional styling included
  • Tons of customizable options

For more information/Options visit : https://dhirajkumarsingh.wordpress.com/ultimate-jquery-content-slider-plugin-dg_slider/

Posted by: Dhiraj kumar