J-Unleashed!

On databases, programming and more

Slick way of handling browser-specific CSS issues

Posted by Joe on May 14, 2009

Every web developer eventually comes across a major headache in cross-browser functionality. My most recent one was with the alignment of text that follows a radio button. Vertically aligning that text with text that comes before a radio button is a bit of a pain. The easiest way to handle this is to use a table and set the valign attribute to middle, like so:

<table>
    <tr>
        <td valign="middle">Select:</td>
        <td valign="middle">
            <input type="radio" name="fruit" />Apple
            <input type="radio" name="fruit" />Orange
        </tr>
    </tr>
</table>

In this example, depending on your browser, you might see the text “Apple” and “Orange” sit lower than the “Select:” text. In Safari and Opera, this renders just fine. In IE, the text is 2 pixels lower and in Firefox, the text is 1 pixel lower. If we design for IE, then Firefox will be 1 pixel above, and Safari and Opera will be off. This is a case where browser-specific CSS is necessary, but you wouldn’t necessarily want to create a whole new stylesheet for it. Enter CSS Browser Selector by Rafael Lima. This nifty little piece of javascript lets you use browser-specific classes in your existing stylesheet. In this case, the solution was simple. First, we change the HTML a bit to put the text following the radio buttons in a label with a class named radio.

<input type="radio" name="fruit" /><label class="radio">Apple</label>
<input type="radio" name="fruit" /><label class="radio">Orange</label>

Then, we reference the small javascript file in our HTML header:

<script type="text/javascript" src="css_browser_selector.js"></script>

Finally, we add the browser-specific CSS to our stylesheet:

.ie label.radio {
    position: relative;
    font-weight: normal;
    top: -2px;
}

.gecko label.radio {
    position: relative;
    font-weight: normal;
    top: -1px;
}

label.radio {
    font-weight: normal;
}

Yep, it’s that easy. Now, IE and Firefox (gecko) render properly. Safari, Opera and other browsers just fall through to the last label.radio.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>