Ask SM [CSS/JS]: Divs of Equal Height, Dealing with IE 6

Advertisement

This is our third installment of Ask SM, featuring reader questions about Web design, focusing on HTML, CSS and JavaScript. In this post we’ll cover how you can take care of a smooth page scrolling and Internet Explorer 6 bugs. You’ll also learn how to aggregate RSS Feeds, how to create dynamic width list images and how to create div-containers of equal height.

If you have a question on HTML, CSS or JavaScript, feel free to reach me (Chris Coyier) using one of these methods:

  1. Send your question by email to ask [at] smashingmagazine [dot] com.
  2. Post your question in our forum1
  3. Or, if you have a quick question, just tweet us @smashingmag2 or @chriscoyier3

Please note: I will answer as many questions as I can, but I will certainly not be able to answer them all. I hope that you will use the forums to post questions because that will give you an opportunity to get help from the community as well.

Smooth Page Scrolling

@Mango_Juice4 writes:

What is the best JavaScript method for a smooth page scroller?

Hey Mango_Juice, jQuery has the ability to do animated scrolling, using its animate function and the “scrollTop” parameter. Karl Swedberg covers this technique5 on his great website Learning jQuery.

The best way to handle it is to set the scroll targets with hash tag links (e.g. #about) on your page. You set your “href” value in the anchor links to “#target”, and then that link will jump to the page element on that page with “target” as its ID. This means it will work regardless if JavaScript is enabled or not.

For the majority of users, who do have JavaScript enabled, we’ll intercept the clicks on those links and scroll down to them (or up), as needed. Here is the code that makes it happen:

$(function(){
    $('a[href*=#]').click(function() {
    if (location.pathname.replace(/^//,'') == this.pathname.replace(/^//,'')
        && location.hostname == this.hostname) {
            var $target = $(this.hash);
            $target = $target.length && $target || $('[name='   this.hash.slice(1)  ']');
            if ($target.length) {
                var targetOffset = $target.offset().top;
                $('html,body').animate({scrollTop: targetOffset}, 1000);
                return false;
            }
        }
    });
});

View Demo6 | Download Files7

Dynamic Width List Images

Giedrius writes:

Is it possible to create a list with CSS that has the text aligned to the right side, but on the left side has an image taking up the width of the remaining space?

Hey Giedrius, when I first read your question, I thought immediately of a recent post on Web Designer Wall, CSS: Menu List Design8. Nick La uses some clever positioning techniques to build a flexible text-based list mimicking standard menu design. You know, the kind that has a little dotted line that connects the text on the left to the price on the right.

But then as we talked, it was clear you needed something different. Because the image has to have a gradient that isn’t horizontally repeatable, we literally need to use an inline image and set its width as needed. CSS alone isn’t capable of performing calculations and effecting DOM elements like that, so let’s enlist jQuery for the job.

First, the completely normal unordered list in HTML:

<ul>
	    <li>Lorem ipsum dolor sit</li>
	    <li>Aliquam</li>
	    <li>Vestibulum auctor dapibus neque</li>
</ul>

The only thing to note is that the length of text in each list item varies significantly. So let’s think through what we need to do:

  • Measure the full width of the list item.
  • Measure the width of the text inside.
  • Append the image to each list item.
  • Set the width of the image to (full width) – (text width).

Here is how I did it with jQuery:

$(function(){
	$("li")
	  .wrapInner("<span></span>")
	  .prepend("<img src='images/listimage.png' />");
	var listWidth = $("li").width();
	$("li span").each(function(){
	      var itemWidth = $(this).width();
	      var imageWidth = listWidth - itemWidth;
	      $(this).parent().find("img").width(imageWidth - 10).height(1);
	});
});

pointy list

View Demo9 | Download Files10

DIVs of Equal Height

Adrian Engelbrecht writes:

How is it possible to have two divs, one with the navigation and one with the content, that always have the same height. Is that possible?

Hey Adrian, there are actually a lot of different ways to do this, but everyone would agree that none of them are as easy as they should be with CSS.

equal height columns

1) Fake it with Faux Columns.
If you just need two divs to look like they are the same height, but not necessarily be the same height, this is the easiest method. You can read about Dan Cederholm’s faux-columns method11 here and see a simple example here12.

2) Use Tables or CSS Tables.
Obviously, you know that using tables for layout is bad mojo, but if it gets you out of a tough spot once in a while, the world will forgive you. So rather than using divs, you could bust out table cells to do this, because in the same row they are always the same height. CSS tables are a hot new technique (personally, I still have serious doubts), but they may help as well. Check out this tutorial13 on NETTUTS.

3) Use Absolute Positioning.
If you know one column is going to be taller than the other, you can use absolute positioning to accomplish this task. Simply wrap both of them in a div with position: relative;. Then have your main column grow to however large it needs to be, pushing the wrapper out. Then absolutely position the other column with both top: 0; and bottom: 0;, and a fixed width along one edge. Dan Rubin has more about this technique here14.

4) Use JavaScript.
I generally avoid JavaScript for anything layout-related, but if you aren’t worried about that, you could possibly use JavaScript to set equal heights. JavaScript has the power to measure elements, compare and perform calculations and all that other magic necessary to get the job done. Take a look at this jQuery plug-in15.

Aggregating RSS Feeds and Implementing Them on a Website

Kyle Steed writes:

Are there any free services that can take RSS feeds from different locations and combine them into one feed that I can use? Then once combined, is it easy enough to implement on a website and style using CSS?

Hey Kyle, yes, there is such a free service. Whenever I need to work with external RSS feeds and integrate them in a website, I turn to SimplePie16, which is a brilliant and free PHP class for doing just this.

I put together a little demo for you, which smashes together the CSS-Tricks and Smashing Magazine feeds and displays them on a page.

View Demo17 | Download Files18

pointy list

It was pretty easy to do. First I include the SimplePie file on my page and set up the options that I want:

<?php

    //get the simplepie library
    require_once('inc/simplepie.inc');

    //grab the feed
    $feed = new SimplePie();

    $feed->set_feed_url(array(
    	'http://feeds2.feedburner.com/CssTricks',
    	'http://smashingmagazine.com',
    ));

    //enable caching
    $feed->enable_cache(true);

    //provide the caching folder
    $feed->set_cache_location('cache');

    //set the amount of seconds you want to cache the feed
    $feed->set_cache_duration(1800);

    //init the process
    $feed->init();

    //let simplepie handle the content type (atom, RSS...)
    $feed->handle_content_type();

?>

Now you have an object loaded with RSS goodness. This loop will spit out the feeds in order of date:

<?php foreach ($feed->get_items() as $item): ?>

	<div class="chunk">

		<h4 style="background:url(<?php $feed = $item->get_feed(); echo $feed->get_favicon(); ?>) no-repeat; text-indent: 25px; margin: 0 0 10px;"><a href="<?php echo $item->get_permalink(); ?>"><?php echo $item->get_title(); ?></a></h4>

		<p class="footnote">Source: <a href="<?php $feed = $item->get_feed(); echo $feed->get_permalink(); ?>"><?php $feed = $item->get_feed(); echo $feed->get_title(); ?></a> | <?php echo $item->get_date('j M Y | g:i a T'); ?></p>

	</div>

<?php endforeach; ?>

Clearly, you have everything, both the markup and CSS, to fully control all of these elements now. The SimplePie website has some nice tutorials on it (including screencasts). Refer to the API Reference19 to find all the stuff you can get out of the object.

Dealing with IE 6

@chrisjlee20 writes:

Best practice/workflow for designing for IE 6?

Hey Chris, ain’t IE 6 fun? It’s been a hot topic for a long time now, all of this business about how and what to support. jQuery does a fantastic job of abstracting all of the cross-browser pains for JavaScript, but unfortunately we don’t have such magic for CSS.

IE Bugs

The fact is, we still have to deal with IE 6 when we are creating websites intended to cater to as wide an audience as possible. At work, I think every single major client we have uses IE 6 at their desk. Makes me want to cry some days, but that’s just one of the painful parts of our job and we’ve got to live with it.

The more you deal with it, the better you become at avoiding IE 6′s common pitfalls and quickly fixing bugs. Here are some of the most common ones21. To fix them, never use browser hacks. Hacks simply aren’t needed, because you can use conditional comments22 to serve up special styling just for IE.

If you’re not comfortable dropping IE 6 support, Simon Clayson has an elegant workaround23:

<!--[if !IE]><!-->
<link rel="stylesheet" href="my_gorgeous_layout.css" type="text/css" media="screen" />
<!-- <![endif]-->

<!--[if gte IE 7]>
<link rel="stylesheet" href="my_gorgeous_layout.css" type="text/css" media="screen" />
<![endif]-->

<!--[if lte IE 6]>
<link rel="stylesheet" href="textonly.css" type="text/css" media="screen" />
<![endif]-->

This will serve up your regular style sheet to all other modern browsers and serve up a special style sheet, starting from scratch, to IE 6. This special “textonly.css” could contain only very basic text styling so that the website is usable but mostly unstyled.

Help us to improve the “Ask SM”-section!

Please feel free to suggest improvements for our “Ask SM”-section. Do you miss something? Would you like to change something? Please let us know in the comments!


(al)

↑ Back to topShare on Twitter

I create websites and help others create better websites through writing and speaking. I consider myself a lucky man for getting to work in such a fun and rewarding field.

  1. 1

    Fantastic, I always struggle wit getting my desigs to work on alternate browsers, though I struggle a lot with Opera to be honest. :)

    0
  2. 2

    cool stuffs, but already seen…

    0
  3. 3

    Opera is the only webbrowser that passes the acid test, so I guess you’re using some things the wrong way…

    0
  4. 4

    Simon Harlinghausen

    February 20, 2009 5:03 am

    Actually we try to get every code validated.
    And don’t care too much about Opera, more
    about IE6.

    0
  5. 5

    You should implement the smooth scrolling in Smashing Magazine. :)

    0
  6. 6

    @joggink, get your eyeballs washed, its not the only browser that passes the tests -_-”

    And using conditional comments @ stylesheets is just wrong. I have yet to find a case where I need to use conditional comments to fix an IE bug.

    0
  7. 7

    I used the equal heights plugin as the basis of implementing faux columns, without the hacks, figure 4% non-javascript I can live with.

    I didn’t like how the equal heights plugin added scrollbars on overflow, so I ended up just using their idea to implement my own solution. One problem I encountered with the javascript solution was the upon resize things went awry, so I came up with my own solution: http://notsurereally.wordpress.com/2009/02/07/jquery-adjusting-div-heights-on-window-resize/. IE8RC1 has a bug with the adjusting upon resize event, apparently it will be fixed in final release (thank god!).

    0
  8. 8

    @joggink, not only opera, but also safari, internet explorer 8, and firefox have passed these tests.

    0
  9. 9

    Another way to solve the “equal heights” problem is to use the “large negative bottom-margin/large positive bottom-padding”-method (I don’t know if it goes by any other name). It’s pure css, works in all browsers and doesn’t require background images.

    0
  10. 10

    @V1: what are your reasons to say, conditional comments for stylesheets is wrong?

    0
  11. 11

    <!–[if no0b]–>
    use conditional comments
    <!–[endif]–>

    Seriously, IE is not that hard

    0
  12. 12

    About your DIVs of equal height – why go through the trouble of comparing heights of elements “and all that other magic necessary” when you can simply set both divs height to the height of their parent via jQuery? Regardless of whether the content in the navigation or the main content grows larger than the other, the parent still contains both and will have a height being pushed by either of those children. Maybe this is all you were getting at, your explanation just made things sound quite convoluted.

    0
  13. 13

    I agree with V1.

    Start with your markup and then do your CSS. I’ve never used an ie6 hack and if I encountered any ‘bugs’, I just rework the markup a bit.

    0
  14. 14

    So – very nice! But some of them is very old stuff. Sorry, but isn´t it right, that CC´s slowing down the site´s performance? For some little Hacks (like a simple star hack) it seems better to use them in one CSS file.

    0
  15. 15

    The smooth scrolling thing is pretty cool, but in Opera when you click on the “top” link in the example, it doesn’t scroll smoothly. It jumps to the top then has some sort of text seizure. Any idea what might be causing that?

    0
  16. 16

    I love that IE bug image!

    0
  17. 17

    you can do equal hight divs by placing both in a parent div and setting all of these ids to floats.

    Also, as for page scrolling MooTools has a very easy to use scrolling feature that uses the John Resig’s (creator of jQuery) transitions.

    As for anything JavaScript related I would suggest MooTools over jQuery. jQuery is exceptionally fast with selectors, but unless if you are using heavy heavy scripting the overhead is marginal. MooTools is more fun.

    0
  18. 18

    @Steve You’d rather rework markup and use an extra hour (at least) of your time messing with the css again than add a min-width: 400px; *width: 400px; or something like that? Kudos to you but my deadlines are too strict to be doing that on anything but small personal projects.

    0
  19. 19

    Chris your missing the negative margin equal height column trick. This is probably the easiest way to do equal height columns and it works in every browser I’ve tested.

    The general idea is that you give your columns a large negative bottom margin and an equally large bottom padding. Then wrap the columns in another container and set the container’s overflow to none. The only catch with this technique is that you can’t have a bottom border on the columns, however you can put a bottom border on the container.

    0
  20. 20

    Nice stuff,

    But there is one issue with the dynamic width menu design: end user text size changes makes the list look ugly…

    0
  21. 21

    Surely using a

    0
  22. 22

    @Timothy – Simply placing floating divs inside of a parent div does not set the height of the floated divs to the parent div. If you have background colors or borders that you want to line up correctly, this will not happen with just floated divs. Are you doing something additional that I’m missing?

    0
  23. 23

    “Obviously, you know that using tables for layout is bad mojo, but if it gets you out of a tough spot once in a while, the world will forgive you.”

    Will the visually impaired world forgive you though? I think not.

    0
  24. 24

    You can also add clips from Google Reader to your site for free. Just create a folder for the items you want to display, set it to “shared” and you can grab the necessary code in your Google Reader settings by clicking on “add a clip to your site.” There are even some customization options right there.

    Very easy to use and nothing to install.

    0
  25. 25

    @Paul: I used to think the same way, I used hacks like the one you mentioned all the time until I came to realize two major fallbacks to this method. First, it makes the code horribly confusing when you have to go back in to perform edits. Generally it’s also more fragile, the smallest addition or removal of something and it all comes down like a house of cards. Second, hacking it up for the browsers we’re using at the moment is fine but causes problems if the site is still around when newer browsers (the FF3 and IE7-8 of the world) roll around. I’ve noticed my IE6 hacks actually causing issues in newer browsers. So yeah deadlines are important but a little prevention goes a long way, especially if you intend on supporting your code for several years to come.

    Also, I wanted to comment on the “Dynamic Width List Images” portion. I noticed that it breaks fairly easily when you increase/decrease the text size. I haven’t had much time to play around with your code but isn’t there a way to let it break more gracefully? I’ll try to mess around with it later to see if I can come up with something.

    0
  26. 26

    I liked the link to css-tricks.com regarding CSS bugs in IE6. While I knew about most of the bugs, there was one that I hadn’t heard of. I think each designer needs to experience these bugs and work with CSS enough before they even know what is going on. My opinion is that a solid CSS/XHTML design shouldn’t require hacks or conditional comments.

    0
  27. 27

    Great stuff – some fascinating things there, especially the dynamic width lists!

    0
  28. 28

    Just a tip for handling IE bugs… don’t know if someone else posted this already, as I didn’t read the comments here.

    Visit: http://code.google.com/p/ie7-js/

    This script automatically handles the IE problems, and even handles IE png transparency issues, it has been a godsend for me!

    0
  29. 29

    In the conditional comments, I would not use gte 7 so that IE8 actually has a chance to render correctly. Was this tested with IE8?

    0
  30. 30

    As annoying as IE6 is, the IE Bug logo in this article is amazing. Links?

    0
  31. 31

    A better resource for info on IE bugs is Position is Everything.

    The scrolling demo got kinda weird in Opera when you clicked the back to top links.

    0
  32. 32

    <blockquote cite=”
    use conditional comments

    Seriously, IE is not that hard”>

    Yeah if your worried about IE Only.

    0
  33. 33

    Great “Ask SM” once again, love to see more of these.

    0
  34. 34

    Nice but nothing new under the sun here…

    0
  35. 35

    There’s a bug in the jQuery code.. This line:

    $target = $target.length && $target || $('[name=' this.hash.slice(1) ']');

    Should be this instead:

    $target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');

    It was missing the + concatenation symbols.. Also worth noting is that the name=”” attribute is deprecated in XHTML, which would mean you’d have to target id=”” attributes instead.. If you want to use this in XHTML replace the same line with this:

    $target = $target.length && $target || $('[id=' + this.hash.slice(1) + ']');

    Great function, by the way.. Works perfectly (once it works ;)

    0
  36. 36

    I thought this was a great ‘equal heights columns’ article: http://matthewjamestaylor.com/blog/equal-height-columns-cross-browser-css-no-hacks

    0
  37. 37

    good stuff like every time when appear a new post here, no matter it’s about graphics or tricks :)
    About IE6 what can I say, most users of my websites are using unfortunately IE6. Sad but true.

    0
  38. 38

    Addicted to SM.waiting for next article

    0
  39. 39

    As long as everyone is going to lengths to make websites *work* in IE6, people will not see any reason to update (“security” is too much of an untangible concept for most users) to a newer browser.

    The day that design implementers finally state that they do not cater for a crap browser anymore is the day that people will upgrade. If your customers are still using IE6, pull out the long list of security holes in IE6 and send that to them.

    Any company that does not enforce the usage of an up-to-date browser (not cutting edge necessarily) desperately needs to rethink their IT team employment strategy.

    On my projects, if it works ok in IE6 great – if not, I don’t care. My customers pay me to make them see why.

    0
  40. 40

    Really enjoyed that article, lots of interesting stuff. Thanks.

    0
  41. 41

    @juro: Care to share a link to that long list of IE6 security holes? :)

    0
  42. 42

    Ahout RSS aggregation, there is also Yahoo Pipes that offer a powerful way to aggregate and filter RSS feeds.

    0
  43. 43

    very nice !!

    I guess I have about 1 million questions in my Mind.. time to write you a few Emails :)

    0
  44. 44

    @John, not off hand – but consider this: if a user has not upgraded IE6, how big is the chance that the user has installed security patches?

    0
  45. 45

    I think #17 (Timothy) has a good idea. You just need to make sure the container of the two columns is the same color as the smaller column. The columns don’t actually have an equal height, they just look like it because the smaller column(s) match the background color. You can do this with more columns but it gets complicated (JavaScript and such would make it easier). You can even make the columns look separated by changing the border colors.

    0
  46. 46

    The divs of equal height tip is a great tip. For the longest time, I would like to say, however, that in some browers using javascript to set equal heights slows down the rendering of the page in regards to CSS. However, this only happens when the css has been compressed!

    Just a friendly tip :)

    0
  47. 47

    Another great Ask SM, really enjoying these posts!

    About IE6: People saying that IE6 hacks and conditional comments are never needed, so long as you’re a good coder, that’s being optimistic in my opinion. There are definately situations where IE6 bugs become a problem even when the XHTML/CSS is very well set up. For example a design done by another person / agency that might not know as much about coding, or a design that has been compromised by unusual wishes / requests from the client. Also stuff like incorporating transparency and PNG images in a page always brings up some form of IE6 targetting, be it through CSS or JS.

    Granted, in 90% of cases IE6 hacks are a result of a programmer’s lack of experience (or lack of willingness to find a better solution). But in that other 10% of cases, targetting IE6 specifically is needed, and it will be needed for at least another one or two years untill IE6 is finally put out to pasture for good. Vista and Windows 7 will need to become way bigger before this will happen, since XP users don’t all seem to want to update.

    0
  48. 48

    @juro

    That kind of thinking may work for a site like SmashingMag. Let’s be honest, most of the people here are using something other than IE6. Probably Firefox, Safari, Chrome, you name it.

    But it is dangerous to think like that in the real world. I think IE6 is still somewhere around 20% general usage, probably a bit less by now. That could equate to a good chunk of people you just, “don’t care,” about, on a decent sized company’s site.

    Really, supporting IE6 is not that hard. Do it enough and you get to know the inconsistencies, and making minor tweaks for IE6 just becomes routine. I just don’t think taking some sort of stand is the answer. Eventually, IE6 will fade away (maybe it will take a bit longer than we’d like) and we will have another browser to complain about.

    0
  49. 49

    “Smooth Page Scrolling” errors in Opera Version 9.63 Build 10476

    0
  50. 50

    Great post. Can anyone reccomend a non php multi rss aggregator? (ASP)

    0
  51. 51

    Chris,

    Thanks again for your help with the RSS aggregator. I love how easy it is.

    0
  52. 52

    For CSS/IE6 I do use a script: Google for ‘css browser selector’. works like a charm!!!

    0
  53. 53

    I’ve written a short tutorial covering easy scrolling with jQuery and the ScrollTo plugin.
    Here’s the tutorial:
    http://blog.adriantomic.se/post/75671123/jquery-localscroll-tutorial

    Hope someone finds it useful.

    0
  54. 54

    Good Information

    0
  55. 55

    IE6 ? You mean, the old browser released 7 years ago which is not even supported by Microsoft itself ? The one who has an (crappy) upgrade called IE7 ? Any good tip for Netscape 4.5 too ?

    Anyway, good article content as always

    0
  56. 56

    I get a kick out of the “Don’t use conditional comments” and “why are you supporting IE6?” type of people who always put in their 2 cents in comments.

    If you are working for a small company with small clients, you can talk your clients into ditching IE6. But that just isn’t reality for me. When you’re working on a site the client’s paying at least 10k for, and the “client” that you interact with is either in the marketing or advertising department, they see conversations like this as “excuses”. They don’t care how old their browser is. They didn’t install it, and they can’t upgrade it because of IT policy.

    For example, I’ve run into problem where a flash app I wrote didn’t run on the client’s computer because they were running v9.05 and the Flex2 framwork needed v9.11 (the next dot release). The client was VERY unhappy and couldn’t update their FLASH PLUGIN because of IT restrictions. To even suggest they use a “better browser” is a waste of time and damages client relations.

    Also if your clients are marketers/advertisers, every eyeball counts. You can’t just throw away 30% of your potential revenue because you’re either too inexperienced or too lazy to give them a good experience in an “older” browser.

    “Hacks” are always a bad idea. Once you’ve been around long enough and had to “unhack” previous hacks because a new browers verion wiggs out, you start to see that the simplicity of conditional comments is a godsend. You can sleep at night knowing that anything you put in that stylesheet will only affect the specific browser you intended now and for eternity.

    Conditional comments are also much easier for the next guy who works on the site to understand. It’s much easier to see that “style-ie6.css” puts some weird rule on an element that addresses a bug in IE6 than to try and work out what a hacky rule is doing, or what problem it’s attempting to solve.

    Personally, I only need conditional comments on about 1/3 of the sites I develop, and the average size of the browser stylesheets is around 3 or 4 lines. These usually deal with IE6′s lack of support for min-height and PNG transparency or when you get hit with the peekaboo bug or box model problems.

    0
  57. 57

    @ Austin: You have to float the parent or container div too. It seems weird, but it works.

    0
  58. 58

    http://www.die6.co.uk is a campaign to rid the world of IE6 – lets get rid of it once and for all!

    0
  59. 59

    These are excellent! Thanks so much for the great posts. This one was especially helpful as i was having a div-height problem. Now it’s fixed!

    0
  60. 60

    Николай Конев

    May 19, 2009 12:00 pm

    Интересно, а есть хоть кто-то, кто не согласен с автором? :)

    0
  61. 61

    The RSS tutorial is awesome, but you get a fatal error when you ugrade to the newest version of SimplePie (v1.2).

    0
  62. 62

    i just did this:

    div id = “left_side” class=”equal_height”
    div id = “main_content” class=”equal_height”
    div id = “right_side” class=”equal_height”

    .equal_height {
    min-height:500px;
    height:auto !important;
    height:500px;
    }

    source: http://www.dustindiaz.com/min-height-fast-hack/

    seemed to work great!

    0
  63. 63

    The main issue when agilning the divs is the CSS used. Try different widths. Let’s say you have a wrapper that’s 600px wide. The content and sidebar should amount up to about 598-6 px. So, you can have a content div 398 px and sidebar 200px. That should work. Don’t forget to clear both divs and float them both to one side.If you have any further trouble, e-mail me and I’ll explain the process more thoroughly.

    0

↑ Back to top