8 Javascript solutions to common CSS problems

by Jean. 85 Comments -

CSS are definitely a great technique for web designers and web developpers. Though, cross-browser problems and lack of CSS3 support in modern browsers are a real problem for your creativity. Today, I have compiled a list of 8 common CSS problems that you can easily resolve with help from Javascript.

1- Transparent backgrounds with JQuery


Ah, transparent backgrounds. Due to the fact that IE6 can’t handle transparent png images, this has been a problem for years. Although many techniques are availables in order to solve this recurring bug, this one is really good because it allows you to make any element transparent, without even using transparent png files.

  1. Download theses files and include them in your website:
    http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js
    http://design-forge.ro/projects/opensource/transBG.jquery.plugin.js
  2. Adapt the following code to your own needs and paste it in the head part of your html document, or even better, in a separate .js file. Basically, Just use the transBGdraw() function on each element you’d like to make transparent.

    $("#id").transBGdraw();
    $("#menu").transBGdraw();
    $("#container").transBGdraw();
    
    // !!!IMPORTANT!!!
    // if you use tagnames or classes, make sure every object affected has a unique id.
    $("div").each(function()
    { $(this).transBGdraw(); });
    
    $("h6").each(function()
    { $(this).transBGdraw(); });
    
    $(".class1").each(function()
    { $(this).transBGdraw(); });
    
    $(".text").each(function()
    { $(this).transBGdraw(); });
    
    $(".information").each(function()
    { $(this).transBGdraw(); });
    
  3. You’re done. Easy, isn’t it?

Source: Cross Browser Transparent Background with jQuery, no css hacks, no *.png files

2 – Include different classes for different browsers


Thanks to Microsoft and Internet Explorer, the bigger problem for every front-end developper is definitely cross-browser compatibility. Even if Internet Explorer introduced conditional tags to include styles only for IE, it can be good to be able to deal with other browsers as well.

  1. This code works with the JQuery framework, so of course make sure you have it installed on your website.
  2. Paste the following code in the head part of your html document or in a separate .js file:
    $(document).ready(function(){ 
        $('html').addClass($.browser); 
    });
    
  3. Now you can preprend your styles with .msie, .mozilla, .opera, .safari or .other depending on the targeted browser.

Source: Avoiding CSS hacks using Javascript

3 – Columns of equals height with JQuery


When using a table, all the columns of this table have the same height. During web design early days, everyone was using tables to style their web pages so creating columns of the same height weren’t a problem at all. But with the rise of CSS, things changed and now, creating columns of equal height isn’t an easy job.
Happilly, here’s a real life saver for everyone looking to create identical columns.

  1. As this code uses the JQuery framework, make sure you have it installed on your webiste!
  2. Paste the following script in a new file and include it to your web page:
    /*-------------------------------------------------------------------- 
     * JQuery Plugin: "EqualHeights"
     * by:	Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
     *
     * Copyright (c) 2008 Filament Group
     * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
     *
     * Description: Compares the heights or widths of the top-level children of a provided element 
     		and sets their min-height to the tallest height (or width to widest width). Sets in em units 
     		by default if pxToEm() method is available.
     * Dependencies: jQuery library, pxToEm method	(article: 
    
    http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/)
    
     * Usage Example: $(element).equalHeights();
      		Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true);
     * Version: 2.0, 08.01.2008
    --------------------------------------------------------------------*/
    
    $.fn.equalHeights = function(px) {
    	$(this).each(function(){
    		var currentTallest = 0;
    		$(this).children().each(function(i){
    			if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
    		});
    		if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
    		// for ie6, set height since min-height isn't supported
    		if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
    		$(this).children().css({'min-height': currentTallest}); 
    	});
    	return this;
    };
    
    
  3. Use the following code to make the top-level childs of an element having the same height:
    $('.container').equalHeights();
    

Source: Setting Equal Heights with jQuery

4 – Cross browser rounded corners


Rounded corners are gorgeous, but they’re also a lot of images and <div> tags, due to the lack of the border-radius CSS3 property in current browsers.
This JQuery script allows you to round any element. Sweet, isn’t it?

  1. One more code that works with JQuery, so double check you have it installed on your website.
  2. Download this file and include it in your html page.
  3. Once done, use the following code to round a div:
    DD_roundies.addRule('.myContainer', '8px');
    

Source: Achieving Rounded Corners in Internet Explorer for jQuery UI with DD_roundies

5 – Fixing IE overflow problem

One more annoying IE problem is the rendering of the overflow property. Happilly this code can help.

  1. Simply paste the following Javascript code in the head part of your html document, or in a separate .js file:
    window.onload = function () {
      // only apply to IE
      if (!/*@cc_on!@*/0) return;
    
      // find every element to test
      var all = document.getElementsByTagName('*'), i = all.length;
    
      // fast reverse loop
      while (i--) {
        // if the scrollWidth (the real width) is greater than
        // the visible width, then apply style changes
        if (all[i].scrollWidth > all[i].offsetWidth) {
          all[i].style['paddingBottom'] = '20px';
          all[i].style['overflowY'] = 'hidden';
        }
      }
    };
    
  2. The code, which will only apply to IE, will look for all elements having the well known overflow problem, and fix it. Althought this can be done in pure CSS, this Javascript solution is interresting.

Source: Fixing IE overflow problem

6 – Vertical alignments


In CSS, vertically centering an element within its parent isn’t always an easy thing, and this is why Javascript can help here.

  1. Simply paste the following code in a separate .js file or in the head section of your html document:
    function AlignMiddle(Parent,Child) { 
    //Generate content dynamically
       document.getElementById(Child).innerHTML="Hello there, I am dynamically align in the middle using a Javascript."
    
    //Center Vertically
       h = document.getElementById(Child).offsetHeight;
       //var a=Math.round(document.getElementById(Parent).style.pixelHeight/2);
    
       var a=Math.round(parseInt(document.getElementById(Parent).style.height)/2);
       var b=Math.round(h/2);
       var c=a-b;
       document.getElementById(Child).style.top=c+"px"; 
    //Center Horizontally
    
       w = document.getElementById(Child).offsetWidth; 
       //var x=Math.round(document.getElementById(Parent).style.pixelWidth/2);
    
       var x=Math.round(parseInt(document.getElementById(Parent).style.width)/2);
       var y=Math.round(w/2);
       var z=x-y;
       document.getElementById(Child).style.left=z+"px";
    }
    

Source: Vertical & Horizontal Centering of ‘div’ object

7 – Image preloading


The Mootools framework have a very nice image preloader. But not everyone like Mootools.

//this is my new preloading method
preloadImages =
{
count: 0 /* keep track of the number of images */
,loaded: 0 /* keeps track of how many images have loaded */
,onComplete: function(){} /* fires when all images have finished loadng */
,onLoaded: function(){} /*fires when an image finishes loading*/
,loaded_image: "" /*access what has just been loaded*/
,images: [] /*keeps an array of images that are loaded*/
,incoming:[] /*this is for the process queue.*/
/* this will pass the list of images to the loader*/
,queue_images: function(images)
{
 //make sure to reset the counters
 this.loaded = 0;

 //reset the images array also
 this.images = [];

 //record the number of images
 this.count = images.length;

 //store the image names
 this.incoming = images;

 //start processing the images one by one
 this.process_queue();
}
,process_queue: function()
{
 //pull the next image off the top and load it
 this.load_image(this.incoming.shift());
}
/* this will load the images through the browser */
,load_image: function(image)
{
 var this_ref = this;
 var preload_image = new Image;

 preload_image.onload = function()
 {
     //store the loaded image so we can access the new info
     this_ref.loaded_image = preload_image;

     //push images onto the stack
     this_ref.images.push(preload_image);

     //note that the image loaded
     this_ref.loaded +=1;

     //fire the onloaded
     (this_ref.onLoaded)();

     //if all images have been loaded launch the call back
     if(this_ref.count == this_ref.loaded)
     {
         (this_ref.onComplete)();
     }
     //load the next image
     else
     {
         this_ref.process_queue();
     }
 }
 preload_image.src = image;
}
}

To begin preloading images use the method preloadImages.queue_images([IMAGES]) where [IMAGES] is an array of images. Everything will be processed internally. There are two methods you can use: onLoaded and onComplete.

onLoaded will fire whenever an image has finished loading. All the properties of the loaded image are available in the variable loaded_image. For example if you want to find the width of the image that just finished loading your code would look like this.

Source: Javascript Image Preloader

8 – Killing IE6


Tired of having apefectly valid CSS code which didn’t display correctly in this obsolete browser for some unknown reason? Then, what about getting rid of this piece of crap? Just insert the following code in your html file, and say goodbye to IE6. It will crash automatically once the page is loading.

function getX( oElement ) {
    var iReturnValue = 0;
    while( oElement != null ) {
        iReturnValue += oElement.offsetLeft;
        oElement = oElement.offsetParent;
    }
    return iReturnValue;
}

Source: 6 html and Javascript codes to crash IE

Comments (85) - Leave yours

  1. Sumesh said:

    Useful hacks there – I’m sure I’ll find transparent background, browser-specific classes and columns of equal height (I use Faux columns, not anymore ;) ),

  2. Aimee said:

    #8 — really? I’d rather have people access a site I did looking broken than be under the impression that I’m such a bad web developer that my site crashes a browser. It would seem very unintentional and not convey the message that they should upgrade.

  3. Pete said:

    I am concerned at the notion of advocating crashing the user’s browser – exploit of a bug – especially when an estimated 20% of users *are still using it* for some sites. Particularly in the corporate world, where many intranet sites were built for IE6 and it is too time-consuming/expensive to upgrade.

  4. Paul Irish said:

    FYI the #2 technique doesnt work anymore. It gives the error:
    TypeError: (classNames || "").split is not a function

    Here is a a revised version that works:

    jQuery.each(jQuery.browser,function(brow,bool) {
    !!bool && jQuery(“html”).addClass(brow);
    });

  5. Free Webmaster SEO Tools said:

    I would love to kill IE6, I have a niche site that no matter what I have tried will not display properly in IE6 and quite a few visitors STILL use it??!!! Why I will never know. Will try these hacks to see if it will work
    Thanks

  6. teddY said:

    Thank you for sharing! I guess one of the more important ones is the jQuery PNG fix – I’ve tried countless of other Javascript-based PNG fixed and so far, the jQuery one worked like magic for me. The IE6 overflow problem is also one that can only be effectively circumvented using Javascript. There are CSS fixes out there, but jQuery does a better job. Kudos for plugging that method!

    Crashing IE6 sounds like an awesome way of getting back at Microsoft (and Bill Gates), but is it worth the effort to chase visitors using IE6 visitors away? Perhaps by force loading a lightbox containing a warning message will suffice for IE6 users. But then again, it’s all up to personal preferences. I guess many designers would love the IE6 crasher script, heh!

  7. Blake Haswell said:

    I can’t believe you’re suggesting purposefully crashing IE6. I really hope that’s a joke, but even so it is quite possibly the worse joke in the history of the world. Ever.

    I know how terrible IE6 is, I deal with it every day, but stopping people from accessing your site because of the browser they use is irresponsible and completely against the spirit of web standards.

    Boo.

  8. Jean-Baptiste Jung said:

    @Glyph & @Blake Haswell: The IE6 crash solution is listed here, people are free to implement it – or not – on their website.
    Agree with you that it is against the spirit of web standards, but using IE6 is against the spirit of web standards either ;)

  9. smashill said:

    I still dislike supplementing my code with java or flash. It really depends on the sites you create, but for information sites I will always make sure that my page looks the same with and without noscript turned on.

  10. Linkit 24.3. - 24.3. | Valontuoja said:

    [...] 8 Javascript solutions to common CSS problems CSS are definitely a great technique for web designers and web developpers. Though, cross-browser problems and lack of CSS3 support in modern browsers are a real problem for your creativity. Today, I have compiled a list of 8 common CSS problems that you can easily resolve with help from Javascript. [...]

  11. Martin Fister said:

    Including different classes for different browsers is a good idea. It’s hard getting your code to work right for everything, and that’s a neat way to make it adapt to the situation.

  12. designtick.com said:

    8 Javascript solutions to common CSS problems…

    CSS are definitely a great technique for web designers and web developpers. Though, cross-browser problems and lack of CSS3 support in modern browsers are a real problem for your creativity. Today, I have compiled a list of 8 common CSS problems that y…

  13. Listen To Hip Hop Music said:

    I have to admit, I like the idea of using JS for rounding corners. It definitely saves a lot of hassle. I’m familiar with image preloading though it seemingly always skips my mind. I think it would come in handy with my site due to the high number of images that I use (almost always one per post). The only one of these I don’t understand is the idea of crashing IE6. While it is atrocious, that would hurt my visitor-base tremendously, as believe it or not, people still use IE. It seems like for every person I try to convert, 4 more IE users pop up. It’s really terrible.

  14. Hazel Q. said:

    Wow! Nice list, especially the transparent background and rounding corners solution. The last solution is quite funny :) ….
    Thanks for the post!

  15. smashill said:

    @listen to hiphop
    yeah, I can feel that too, I don’t understand why people still use the explorer, I just don’t like it and I hate cross boarder testing and coding, would be so much easier with one perfectly working browser instead of 10000000

  16. Firany said:

    I’ve been always outsourcing this kinda stuff to other webmasters. I’m glad I’ll be able to take care of all of that by myself from now on. Thanks.

  17. Anthony Alexander said:

    I prefer ‘programming’ different browsers, than multiple platforms and hardware configurations, which is probably why so many C++ people are turning web developer. My only real gripe with IE is the out dated rendering engine, it used to be the best before my framework hit 130k :)

  18. Silenceway » Soluciones con Javascript para problemas con CSS said:

    [...] 8 javascript solutions to common css problems es un artículo que nos muestra como usando javascript podemos solucionar algunos problemas que se tienen con css. Las ocho soluciones son: – Fondos transparentes con JQuery – Incluir diferentes clases dependiendo del navegador – Columnas de igual alto con JQuery – Esquinas redondeadas para todos los navegadores – Arreglando el problema ‘overflow’ en Internet Exlporer – Alineación Vertical – Precarga de imágenes – Matar el IE6 Todas las técnicas son interesantes y fáciles de implementar. [...]

  19. ganesh said:

    Thanks for all who are behind these excellent scripts..but for me Killing IE6 is not working..?

    Killing IE6:

    Thanks for one and all

  20. Number One On Google said:

    Awesome.. This is a fantastic resource, that I wish I had found months ago. It would have saved me weeks worth of wasted work..

    Thanks you for putting thsi awesome resource together.. Much appreciated.

    K.

  21. Nicolas Prudhon said:

    That’s a very interesting collection there! I’d never had thought of using Javascript to compensate CSS issues.

    As a SEO, I have taken the habit to forsake Javascript as much as possible, and usually look at CSS or PHP; nonetheless, some of the hacks you introduce here are worth taking a look at!

  22. Kotlina Klodzka said:

    You definitely need to work on Opera compatibility. I know that it doesn’t have a lot of the market but for example at home I use it exclusively and if any features of the site don’t work in Opera I just stop using the site alltogether.

  23. Joshua Issac said:

    Best way to respond to your customers: crash their browser!

    They’ll think your site has spyware and you will lose out on potential customers. And if you think IE6 is obsolete, you need to do a bit more research.

  24. Jean-Baptiste Jung said:

    @Joshua Issac: Any good web developer will tell you that IE6 is obsolete. Come on, we are in 2009 while this piece of crap was released in 2001…
    IE6 doesn’t deserve anything else than crashing. Same for people who use it.

    • Joshua Issac said:

      When I wrote that comment, IE6 had a market share of about 20%, after IE7 (30%) and Firefox 3 (28%). That is a fifth of the global browser market share, then more than Opera, Chrome and Safari put together. So IE6 certainly was not obsolete as it was still the third most popular browser in the world.

      In 2009, it would have been better to design your site to work in just IE7, Firefox 3 and IE6, rather than making it work in all the other browsers but leaving out IE6 because it was still use widely, more so than all the alternative browsers, sans Firefox 3. The situation is different today, in 2012. IE6 is obsolete now, with only 1.5% of the market share.

      But if you think that your visitors/customers deserve crashing because of their browser, then you do not deserve to have them as customers. I am sure that a more competent developer would gladly make a page that works in IE6 and get all those customers you drove away. This would have been especially true in 2009, when IE6 had 20% market share.

      (Source: StatCounter)

  25. Ian said:

    oh thats very helpful for me.
    I’m looking for it for a long time!
    Thanks very much!
    Thats very interesting as well~

  26. Juraj said:

    Consciously crashing IE6? Appalling suggestion. I would never hire such web developer.
    I deal with corporate clients so apps I develop must work in IE6 most of the time but let me tell you, there is always a way how to make things work without hacking it into pieces.

  27. Jean-Baptiste Jung said:

    @Juraj: Seriously, man. IE6 is shit. As a developer, I strongly believe that a part of our work is to educate people about what’s better for them. Most intelligent people will easily understand that a browser released in 2001 can’t work as good as one released this year.

  28. Yoke Lee said:

    Nice!

    I would loooooooooove to crash IE just for the sake of avenge my frustration.
    Of coz, I wont do it to my clients’ website… =P

  29. vivek bandebuche said:

    ‘1.1 Setting Equal Heights with jQuery’ is unnecessary, because tables have their purpose and html/css coders now avoid to use them without a good reason. The only one reason is that the table are not enough ‘cool’ now, well that’s wrong. Tables are hard for maintenance when you have lots of nested tables, but tables are good for this example – equal heights, because when you have large page with lot of content, you’ll have wait for browser to load whole page and then to call this script, and the page will flick, and that is ugly. Solution for this is table. User don’t look in your html code, and tables will never disappear from html or be abandoned like you say.
    Just use tables where are they logic for use.

  30. Nick said:

    Couldn’t you just specify a height in css to make columns an equal height?

    And LOL @ killing IE. I would love to do that. What a terrible browser.

  31. Nick said:

    Thank you so much for the vertical alignments fix. This is exactly what I needed for the project I’m working on. Great article.

  32. Sanooj ah said:

    i think this is also a simple method to detect browser
    $(document).ready(function()
    {
    if ( $.browser.msie ){
    if($.browser.version == ’6.0′)
    {
    $(‘html’).addClass(‘ie6′);
    }
    if($.browser.version == ’7.0′)
    {
    $(‘html’).addClass(‘ie7′);
    }
    if($.browser.version == ’8.0′)
    {
    $(‘html’).addClass(‘ie8′);
    }
    if($.browser.version == ’9.0′)
    {
    $(‘html’).addClass(‘ie9′);
    }
    }
    else if ( $.browser.webkit )
    { $(‘html’).addClass(‘webkit’);
    }
    else if ( $.browser.mozilla )
    { $(‘html’).addClass(‘mozilla’);
    }
    else if ( $.browser.opera )
    { $(‘html’).addClass(‘opera’);
    }
    });

  33. Geoff said:

    Hello! I just would like to give an enormous thumbs up for the good data you could have right here on this post. I shall be coming back to your weblog for more soon.

Leave a Reply

Your email address will not be published. Required fields are marked *

Please respect the following rules: No advertising, no spam, no keyword in name field. Thank you!