Solving 5 Common CSS Headaches

Tutorial Details
  • Difficulty: Beginner
  • Completion Time: 15 Minutes

CSS is a relatively simple language to learn. Mastering it, on the other, can prove a little more difficult. Compensating for various browser inconsistencies alone can produce a migraine. In this article, we’ll demystify five of the most head thumping issues that you’ll encounter when building web applications.

Why Are My Styles Not Effective?

We’ve all done this. You think to yourself, “Wow, this text would look great if it were bright red.” (really??) Unfortunately, when you add the necessary styling, your text remains black. How come?

There could be a couple reasons why your styles aren’t taking effect. Needless to say, it can be a nasty problem – especially for beginning CSS developers. First, pay a visit to your CSS file and make sure that there aren’t any typos. I’ve wasted many hours dismantling my documents only to find that I misspelled a word. But, if you haven’t banged your head against the wall at one time or another, you aren’t allowed to call yourself a web developer! Most likely, you’re dealing with a specificity problem. Try adding “!important” next to the style that isn’t taking effect. If it suddenly works, that means you definitely have a “weight” problem. As a matter of good practice, never leave “!important” anywhere in your stylesheet. Simply use it as a way of debugging. Consider the following example:

#wrap #myStyle
{
color: black;
}

Because there is greater specificity here, the color will remain black. By including the additional identifier, “#wrap”, there is more weight on this selector. Consequently, the first style will be disregarded in favor of this one.

How can we solve this issue? You should first check to see if the second style can completely be erased. If it can’t, you’ll simply need to add more specificity to your original selector. We’ll go over the concept of specificity” in much greater detail shortly. Let’s try adding:

#wrap p#myStyle
{
color: red;
}

Now, the text will finally turn red. By adding the additional “p” selector, we’ve added one more point, thus overriding any other styling.

What’s The Difference Between Absolute And Relative Positioning?

Maybe more than anything else, positioning can prove to be an unnecessarily confusing topic for beginning to intermediate CSS designers. The best way to learn is to first tackle absolute positioning. Let’s assume that we have a blank html and CSS document. If we were to then place an image absolutely on the page – say 100px from the top, and 100px from the left of the window’s edges – we could write the following style…

img
{
position: absolute;
top: 100px;
left: 100px;
}
Absolutely Positioned Image

Absolutely positioned elements are positioned in relation to their closest positioned parent elements. In this case, where there are no relatively positioned elements on the page, the image will be positioned in relation to the window.

Now, imagine that we wrapped a relatively positioned div around our image.

<body>
  <div id="wrapper">
    <img src="#" alt="Some Image" />
  </div>
</body>

In order to set a positioning context, we must add “position: relative” to the styling of our parent div.

div#wrapper
{
position: relative;
background: gray; /*Just to see the borders.*/
height: 600px;    /*Because the image is absolutely positioned, we need to force the height.*/
width: 770px;
margin: auto;
}
Absolute Positioning That Is Relative To The Wrapper Div

Now, when we absolutely position the image, it will be positioned “relative” to the “wrapper” division. Keep in mind that if we removed this property, the image would once again be placed in relation to the browser’s window. The “position” property is key here.

Additional Resources

  • CSS Tricks

    CSS-Tricks.com : Absolute Positioning Inside Relative Positioning

    Chris Coyier goes over some practical examples that show exactly how and when to use positioning. Includes a demo and downloadable source code.

    Visit Article

  • DigitalWeb

    Digital-Web.com : Web Design 101: Positioning

    “Let’s shed some light on the shadowy mysteries of CSS positioning. If your CSS skills are limited or even moderate, you will learn what you need to master positioning.”

    Visit Article

How Can I Compensate For Internet Explorer 6′s Double-Margin Bug?

For those who are unfamiliar with the “Double-Margin Bug”, if you float an element and then procede to add margins in the same direction as the float, Internet Explorer 6 will incorrectly double the value. In effect, a left margin of “100px” becomes “200px” in IE6. There are three different remedies that we’ll review.

Change The Display To Inline. The simplest fix, discovered by Steve Clason, is to change the display property of your element.

#floatElement
{
display: inline;
float: left;
margin-left: 100px;
}

Use Conditional Comments. Luckily, changing the display will fix that nasty bug. However, what if, for some reason, you need a different method? Internet Explorer allows you to target different browser versions by using “conditional comments”. Add the following into the head tag of your document:

<!--[if lt IE 6]>
<link rel="stylesheet" type="text/css" href="ie6.css" />
<![endif]-->

In layman’s terms, this code is saying, “If a visitor to your page is using Internet Explorer 6 or lower, import a stylesheet called “ie6.css”. As a result, modern browsers will ignore this statement. IE 6 and below, on the other hand, will implement the file. Now, in our ie6.css file, we’ll need to add some override styling.

#floatElement
{
float: left;
margin-left: 50px;
}

Since we know that IE 6 will double the margins on floated elements, if we reduce the value of the margin by 50%, it will fix our document. This method is particularly appropriate when you have many styles that are targeting IE6 directly. It’s important to contain all of your “hacks” in a centralized location.

Implement The Underscore Hack. There are many ways to target older versions of Internet Explorer directly from our primary stylesheet. Generally, I prefer using conditional comments. However, if I only need to change a single property, I’ll many times use the underscore hack. Consider this following:

#floatElement
{
float: left;
margin-left: 100px;
_margin-left: 50px;
}

Modern browsers will cycle through these properties. When they come to the underscore, they’ll skip the style entirely. On the flip side, IE6 will ignore the underscore and implement the new margins. What we end up with is modern browsers adding “100px” to the left margin. IE 6, respectively, will add only “50px”.

Additional Resources

  • Dustin Brewer

    DustinBrewer.com: CSS Fix For The Double Margin Float Bug In IE6

    Dustin offers a quick explanation for overcoming this bug. Be sure to check out his related tutorials as well.

    Visit Article

  • Position Is Everything

    PositionIsEverything.com : Double Margins

    Make sure that you check out this easy to read article if you are still somewhat confused.

    Visit Article

Is There A Way To Measure How Specific My Selector Is?

Absolutely! Yet, very few people know the exact equation. Many of you probably go by the “keep adding more identifiers until it works” method. Practically speaking, this will work just fine. But, you should know how to calculate the weight of your selectors never-the-less.

First, let’s associate each type of selector with a value.

  • Elements – 1 points
  • Classes – 10 points
  • Identifiers – 100 points
  • Inline Styling – 1000 points

Let’s try to calculate the weight of the following style…

body #wrap div#sidebar ul li a.selected
{
random styling....
}

Referring to our calculator above, we’ll dissect this selector. The body element receives one point. Next, we have an identifier (#wrap). This will add 100 points to the tally. Continuing on, we have “div#sidebar”. How many points do you think this is worth? If you guessed 100 points, you’d be incorrect. You must factor in the “div” element into your weight. The correct answer is 101 points. The “ul”, “li”, and “a” elements earn one point a piece. Lastly, the “selected” class receives an additional 10 points. Adding everything up, we come to a sum of 215.

I recommend that you spend a few minutes and memorize this point system. It will save you a great deal of wasted time when you find yourself in a specificity dilemma!

Additional Resources

  • Smashing Magazine

    SmashingMagazine.com: CSS Specificity: Things You Should Know

    For an in depth explanation of specificity, I highly recommend that you read this article from top to bottom.

    Visit Article

  • Stuff And Nonsense

    StuffAndNonsense.com: CSS Specificity Wars

    Learn the art of specificity in a fun “Star Wars” setting. This is a must read.

    Visit Article

What Is The Best Way To Test My Site In Different Browsers?

A required step when you’re working on a site is to review it in every modern browser: Firefox, Internet Explorer, Safari, and Opera. Step two is to test your site in older version of IE. I recommend that you download IE Tester, which will allow you to view your site in IE 5 – IE 8. The final step is to check all of the less common browsers. Visit BrowserShots.org to view snapshots of your site in every browser available.

Additional Resources

  • IE Tab

    Mozilla.com: IE Tab for Firefox

    Do you hate having to switch between IE and Firefox when testing your site? Why not download IE Tab?

    Visit Article

Any confusing questions that I missed? I’m sure there are plenty. Leave a comment and I’ll try to incorporate them into part two. I’m hoping to turn these “Question and Answer” style articles into an ongoing series.

Tags: tips
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.noblelabs.com noble

    awasome. Its a great help for me.

  • http://webdesign.about.com/ Jennifer Kyrnin

    Thanks. This is a great article.

  • http://none skn

    this is a good article

  • http://www.configuracionvisual.com dlv

    thanks, really great information posted!

  • Jeremy

    You should write about getting two floated columns to line up. Like the typical header two-col footer layout, there are some fundamental issues in building them that many people don’t seem to understand (I know HOW, I don’t know WHY). For instance, in order to get a parent div to wrap around a floated div, you have to set the overflow to a specific value, otherwise your parent div will just be 10px high or so, even if the div inside is 800px high. This doesn’t make any sense to me, but I do it anyway ;)

  • http://gabediaz.com Gabe Diaz

    Don’t forget the html>body CSS child hack, look it up for more details but it’s basically:

    *IE6 Will read these lines of CSS as it can’t read html>body
    #contentmain{
    background-color:#000;
    color:#fff;
    }

    *IE7, Firefox, Safari and others will read these lines of CSS
    html>body #contentmain{
    background-color:#fff;
    color:#000;
    }

    IE6 will display a black background with white text, and other browsers will display a white background with black text. With this hack you specify your margins to specific placements between “regular” browsers and IE6 aka the devil browser!!

    Also if you have a PC and would like to install older versions of IE you can try:
    http://tredosoft.com/Multiple_IE

    When I’m on a PC I use the above, much easier than rendering IE pages or just looking at snapshots of your page in IE6.

  • Sean

    Anyone care to explain why “hello” turns out blue in this one?

    #first #second #third {
    color: red;
    }
    #fourth {
    color: blue;
    }

    hello

  • Sean

    There were supposed to be 4 nested divs where the ID order goes outer to inner: first, second, third, fourth. Stupid me didn’t think about how posting html is a no no.

  • Jatin Meshiya

    This type of article provides information that you should call as “jack” information. We want “master” information. If it is possible then please make tutorials like this with full information.

    It is really very impressive tutorial. We really appreciate your efforts! Keep it up!

  • Eric

    Download Safari – the develop tab really helps so you don’t have to do all that browser-switching.

  • http://www.traceygrady.com Tracey Grady

    This is a seriously useful article. Thanks.

  • http://thedailyapp.com Tommy M

    I used the underscore hack often on a few websites a couple months ago. The problem is that it breaks CSS compliance. Although, curing IE6′s stupidity (margin errors) with IE’s stupidity (an underscore) might be good antidote.

  • Marcos

    Man, this is a great article!!!!
    congratulations.

    p.s. that browsershots.org is perfect !!!!

    best regards

  • http://www.thomasthesecond.com Tom

    Very nice article. I first encountered the double-margin bug a few weeks ago when I was building my portfolio site. I must have tried everything imaginable and then display: inline did the trick. Weird.

  • Pingback: Best of July 2008 | Life as a Web Designer

  • http://tomleo.com Tom Leo

    If the IE Tab FF plug-in works, I well be quite happy. Good article BTW.

  • http://www.tirolocoworks.com Los

    I work on Mac’s at home. So my question is about testing on browsers. But as a Apple user how can I test for Windows users. It seems the only remedy is actually owning or testing on a actual Windows OS. Is there a solution for testing for Windows on a Mac environment? Is there huh, tell me there is Ahhhhh!!! Ha ha. O yea keep up the great work.

  • http://www.ikeris.com Cezary Tomczyk

    For the test compatibility with IE you may use this site: http://ipinfo.info/netrenderer/

  • http://www.manlycreative.com Seth

    Something I do often is style both IE6 and IE7 specific styles in one IE sheet by using the conditionals above but using the standard:

    #my_id { /* Style IE7 */ }
    * html #my_id { /* Style IE6 */ }

    This way I have more control over my site with less stylesheets and conditionals.

  • http://www.diyanswerguy.com/ DIYGuy

    I think your first example is going to cause confusion for some.

    IDs are meant to be used only once per page. The way you resolved the issue will only work if there is only one ‘p’ on the page — that’s a really long read :)

    #wrap p#myStyle
    {
    color: red;
    }

    Instead, you could modify the style as such;

    #wrap #myStyle p
    {
    color: red;
    }

    This way, any ‘p’ within #myStyle will have a different color — thus over riding the cascade — and you don’t have to add individual classes to each ‘p’.

  • http://www.alfredfox.com Freelance Web Design

    I greatly dislike the inconsistencies in IE. Even IE7 is a bit wacky at times. Fortunately there are always many ways to get something done. It’s a good thing too, otherwise there’d be no pleasing anyone!

  • Grant @ BTP

    In the IE6 double-margin solution, you use conditional comments to target (supposedly) IE6 and lower, but the specified conditional comment parameter ‘lt IE6′ actually targets versions of IE lower than IE6 (not including IE6).

    Shouldn’t it be ‘lte IE6′ (Less Than or Equal to) ?

    Aside from that, great article; I definitely learned from the specificity and weight info!

  • http://www.just4freaks.de Starnberg

    thanks for the nice article
    firebug is the best extension i ever used

  • http://www.softclickit.com Eric Levay

    Nicely written and clearly explained.

    Using CSS and relative positioning to me has been the standard for page layout, however with relative positioning when a user re sizes the browser window, the page remains a fixed size causing the page to require scrolling.
    I’d like to know if using percentages would make the page grow and shrink according to the window size resulting in a better planned layout. If so I’d also like to request an article about it.

  • http://muse-design.de Jens Schulze

    Im looking for a possibility using more IE versions to check browser compatibility on one PC!. Can anybody help me?

  • http://forums.thricescene.com/ Dwayne Charrington

    Thanks for the informative article. As it has been mentioned, Firebug is an invaluable source when it comes to CSS debugging.

  • http://www.collagist.com/blog Collagist

    Useful article. As you said CSS is very easy to start with but can get very complicated when you are doing across multiple browsers.

    Are there any special care that one has to take for Opera and Safari? Looking forward to more articles. Appreciate all the additional resources that you provided.

  • http://www.detacheddesigns.com Jeffrey Way
    Author

    @Collagist – Opera and Safari are very standards aware. You shouldn’t have to worry about them too much – other than something small here and there. Just make sure that you validate your code as often as possible. :)

  • http://oyun-siteleri.bloggum.com Oyun Siteleri

    CSS “Cascading Style Sheets” Lessons
    css list style Properties and examples — http://css-lessons.ucoz.com/list-css-examples.htm

  • Pingback: 25 Awesome tutorials for web designers « Narendra Dhami

  • Pingback: 25 Awesome tutorials for web designers « Guiwells’s Blog

  • http://www.onlineworx.net Manchester Web Design

    Fantastic tips – Some valuable resources in this post. Many thanks!

  • Pingback: From free for free » Blog Archive » 25 Awesome tutorials for web designers

  • Dave

    Matt’s comment is a key fact worth knowing — the whole point system thing is like “i before e except after c”: it works to explain some basic examples, but really falls apart and generally teaches an incorrect concept.

    I guess going by the 1-10-100-1000 point system is a decision coders have to make…am I going to understand how specificity actually works or am I going to get things accidentally right and not care because my clients won’t know the difference?

  • http://www.detacheddesigns.com Jeffrey Way
    Author

    @Dave, @Matt – Very good points. It’s true that the base 10 system isn’t 100% accurate. However, I’ve found that it works just fine for my projects – unless I get into some extremely complicated selectors…which is a bigger problem.

    There is a more efficient way to determine specificity – we might write a tutorial on it sometime in the near future.

  • Pingback: Web geliştiriciler için harika paketler

  • Pingback: 25 Awesome tutorials for web designers | Boxed CSS

  • Pingback: 25 Awesome tutorials for web designers | Boxed CSS

  • Krishna Reddy

    It is very nice article

  • Pingback: 9 Top CSS Essential Skills That Every Web designer Should Learn - aComment.net

  • Jatin Meshiya

    I want to know more about selectors. How it works and how, when and where we have to apply it properly. Can anybody put focus on this point? Please….

  • anonymous coward

    litmusapp.com is the real answer to question #5

  • Jatin Mehshiya

    @Jens Schulze: Hello dear. If you want to check all IE versions and more browsers along with their different versions then you can use on site that is bells for us : http://browsershots.org/

    You can check here different browsers with their version and also different OS platforms. Try and check your web designs here and be fear free!

  • Ivan Nikolic

    Nice article, you have one mistake in “How Can I Compensate For Internet Explorer 6′s Double-Margin Bug?” – it should state “lte IE 6″ if you want to target IE6 and lower.

  • Pingback: 25 Awesome tutorials for web designers | 打篮球的手

  • Pingback: RSSA聚合 » 25 Awesome tutorials for web designers

  • http://www.nomad-one.com nomad-one

    excellente’

    I would love to see more CSS bug fixing tuts, one of the areas I experience the most headaches and I think I speak for a large audience out there as well.

    Thanks Ton

  • http://URL(Optional) vinish

    Nice!

  • http://www.abhijitdutta.com abhijit

    Thanks for letting me know about IE tab ….

  • http://www.wazdesign.wordpress.com Wazdesign

    Hey I am CSS and xHTML desiner, thans for the article Really like your article