4 simple techniques to quickly debug and fix your CSS code in almost any browser

Posted by & filed under Articles.

Food Web Application

You have designed the perfect layout for your new and upcoming website. But now converting all that beautiful Photoshop PSD layered file into a pixel perfect code is the challenging part. It is not challenging because you don’t know how to code, but more challenging because different browsers render your code differently, even when you are using a completely valid CSS code to display that awesome semantic HTML5 code you have written. This is even more frustrating when fixing a bug in one browser now becomes a new bug in another browser. Even if that’s not challenging, now imagine you are assigned to fix someone else’s code that’s all over the place. Often time this last case is the one that makes you pull your hair and say numerous WTFs before you completely understand what is going on in their code, because you probably know your entire style sheet by heart and this new code is no where close to any coding convention. However, moment of getting down and dirty with debugging that CSS code is much simpler and less frustrating than before, thanks to these very simple tools and techniques.

1) Inspect Element Tool

Inspect element by far is the best tool to start debugging anything CSS. If you are developing websites, then you need the right set of web development tools. And fortunately Inspect Element is now integrated natively with all modern web browsers as part of their developer tools. This tool enables you to select the specific element in the page that you would like to fix and immediately see what CSS rules are applied to that element that cause your selected element to display that way. All you have to do is just right click and select “Inspect Element” from the context menu.

Now you have full visual access to all the rules that are computed for that element. If you have not selected the right element, you could simply click on the source and pin point the exact element you would like to diagnose. As you see in the screenshot above, now you could tweak your CSS rules. Using the checkbox on the left side of each CSS property you could toggle that property, or even click on the property and change its value, or even hit enter key and add new rules for your element. Even most amazing is how easily it is possible to debug a hover state of an element by simply opening the drop down menu next to the selected element and choose :hover state. As you could see in the right panel, this amazing tool even shows you the style sheet file and line number of the CSS rule that’s being executed in this page. Moreover, it is more comprehensible to understand why our element has a 10px top and bottom padding instead of 5px, because the rule at line 1026 of style.css of our media query CSS overwrites the old rule on line 916 of the same file. It is even possible to see the box model of the selected element with it’s current dimensions without using a third party ruler or measuring tool. Having this wealth of information now makes our debugging job much more easier. Suppose your style sheet email form field is not similar to other input elements and you wonder how you could solve this. You inspect that element and find out that because you are using the new HTML5 input field types, your theme designer has not included any CSS rules  for input[type="email"] so you add this selector to the style sheet.

input[type="text"],
input[type="email"]{
   border: 1px solid #ccc;
}

Google Chrome also has similar developer tools that enable the same features. It is even possible to change your debugging mode to the screen resolution of a device that you would like to test your layout and find out how your media queries CSS is behaving under those conditions.

Chrome inspector

These developer tools have very powerful capabilities even beyond CSS development such as DOM inspection, JavaScript profiling, JavaScript Console, resource monitoring tools, and whole other set of features that need their own tutorial section beyond this article.  As you could see in the picture above, in Chrome developer tools, it is even possible to emulate different browser user agent, or even emulate touch events such as swiping. With these tools you don’t even need to actively debug your CSS in your smartphone’s mobile browser, at least to some extent.

Chrome inspect element

Which browser’s developer tools is the best is a questions that you will find out by experimenting. At the end of the day it all depends on what you are trying to achieve and if that tool set enables you to get to your final goal. I personally use all these tools to my advantage. Each have something that I like and find helpful when I want to debug my code. For example I find the little square color representation of the hex colors next to the CSS color properties somehow useful, even though I can process the RGB color in my head and get approximate color palate visualization, these small differences make me alternate between these developer tools.

Firebug

Firebug

Firebug was one of the first tools that provided inspector feature. It is one of the most popular web development tools, with almost 3 million average daily users. As of this writing, Firefox CSS debugging tools are adequate enough for me to not use Firebug, however for JavaScript debugging in Firefox I still use Firebug.

Afraid of IE7? Don’t be anymore

Internet Explorer 9 Developer Tools F12

You might be surprised but Internet Explorer even has Inspect Element (Ctrl+B) feature in their developer tools (F12). Although not as friendly as other browsers’ developer tools, still this feature built in Internet Explorer 9 is very helpful for testing your layouts in IE7 and IE8 emulated mode. Back in the days when none of these developer tools were available for debugging old IE browsers, this second technique usually was very handy.

2) Debug in Style

As good as Inspect Element is, sometimes either you do not have access to that tool, such as mobile browsers, or you want to adjust styling of couple of elements in the page instead of just a specific one. I love to know boundaries of the element I am styling, so I know if there is any overflows, or floating issues, or etc… For that reason I add a bright and noticeable background color to the active element I am styling and take the background color out once the styling is done. Sometimes, I go back and forth adjusting these elements, so I just move the debugging code to the end of my style sheet and comment it out, and uncomment it once I need it again. This way I can quickly toggle debugging mode and see how each element is positioned on the screen.

Stylish Debug Code

Which results to …

Stylish CSS Debugging

For this example I just added debug code to the main structure block items in my page. Now I can tell where each post starts and how much gap there is between each post or widget item in my sidebar, and if I want to add a gap between the sidebar and the main content, I can visually see it in bright colors.

The opposite of this is also possible, by defining a series of debug rules, and adding that class to whatever item we want to see. For example, above I have defined a new class called debug with the following code.

.debug{
  border:1px solid red; 
}

and whenever I want to debug any element, I simply add debug class to that element.

<div class="foo debug">Div element with foo and debug classes</div>

3) Debug CSS using JavaScript

This technique is very much similar to above, however sometimes for some strange reasons it happens that the above situation is not feasible. This is a piece of jQuery code that comes to our aid by applying the debug class to foo element, or even adding CSS directly to the bar element in this case.

$(document).ready(function(){
     $('.foo').addClass('debug');
     $('.bar').css('border' : '1px solid blue'); 
});

This situation might happen very rarely, but I know I have used this technique in the past, so it’s good to know.

4) Get to know the Cascade

Some CSS issues are so common like the clearing floats that you will fall in that trap once, and next time you encounter something similar, you know what caused the problem and how to fix it. In general, most of the CSS issues are easy to solve if you know how the CSS rules override each other. For example, more specific selectors will override more general ones, or ID selector overrides class selector, or !important declaration takes precedence over a normal declaration. Getting to know the Cascade will help you resolve your Cascading Style Sheets code faster.

Here is an example straight from W3C spec on how selector specificity works.

Some examples:

 *             {}  /* a=0 b=0 c=0 d=0 -> specificity = 0,0,0,0 */
 li            {}  /* a=0 b=0 c=0 d=1 -> specificity = 0,0,0,1 */
 li:first-line {}  /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */
 ul li         {}  /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */
 ul ol+li      {}  /* a=0 b=0 c=0 d=3 -> specificity = 0,0,0,3 */
 h1 + *[rel=up]{}  /* a=0 b=0 c=1 d=1 -> specificity = 0,0,1,1 */
 ul ol li.red  {}  /* a=0 b=0 c=1 d=3 -> specificity = 0,0,1,3 */
 li.red.level  {}  /* a=0 b=0 c=2 d=1 -> specificity = 0,0,2,1 */
 #x34y         {}  /* a=0 b=1 c=0 d=0 -> specificity = 0,1,0,0 */
 style=""          /* a=1 b=0 c=0 d=0 -> specificity = 1,0,0,0 */
<HEAD>
<STYLE type="text/css">
  #x97z { color: red }
</STYLE>
</HEAD>
<BODY>
<P ID=x97z style="color: green">
</BODY>

In the above example, the color of the P element would be green. The declaration in the “style” attribute will override the one in the STYLE element because of cascading rule 3, since it has a higher specificity. If you think this example is hard to understand check this article on CSS Order of Precedence.

Final notes

Achieving pixel perfect results is hard due to different renderings by different browsers. Some old browsers do not support full CSS3 or HTML5, so check HTML5Please community project to see if the syntax you are trying to use is supported by majority of the browsers. However, you could optionally use fallbacks or polyfills  to provide missing features for browsers that do not support full CSS3 or HTML5 implementation.

5 Responses

  1. Oğuz Çelikdemir

    Dear Norik,

    thank you for great article. I have a question that isn’t related with this topic. Could you please give me the link of the picture that used for this tutorial ( top of the page )? I loved the aesthetic :)

    Reply
  2. Rob Levin

    Nice debugging tips. I like also letting web developer plugin do outlines on elements and ALS *{ background-color: rgba(0,0,0,0.1) }

    Reply

Leave a Reply

  • (will not be published)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>