Smart Columns w/ CSS & jQuery

Blog » CSS/XHTML » Smart Columns w/ CSS & jQuery

Smart Columns w/ CSS & jQuery

PrintMay 25th, 2009

As I observe other liquid based websites, I see two commonly used techniques on displaying columns, the fixed columns and the liquid columns. There are drawbacks to both that I would like to point out, and later would like to pitch my solution.

Fixed Columns
The great thing about having fixed columns in a liquid layout, is that it will fill up the view port with as many columns as it can fit. But as you can see there will be certain viewport resolutions, where it leaves excess white space where a column was just not able to squeeze in.

Fixed Columns - CSS

Liquid Columns
Liquid columns do not leave any excess white space and fits perfectly within its layout, only downside of this is that we are restricted to having a fixed number of columns per row.

Fixed Columns - CSS

Smart Columns with CSS & jQuery

One solution that would be able to benefit the situations is to take the good of both scenarios and mash it into one.

  1. Allow as many fixed columns to line up across the viewport (as many as it will fit based on the base column size)
  2. Take excess white space and evenly distribute them to each of the columns to complete the full row. This way the columns will always fit perfectly.
  3. Keep a default fixed width as the base, so that the columns are reasonably within the intended columns sizes while maintaining enough flexibility to accommodate for the expandable viewport.

Fixed Columns - CSS

HTML

Start by creating an unordered list that would behave as columns.

<ul class="column">
        <!--Repeating list item-->
        <li>
            <div class="block">
             <!--Content-->
            </div>
        </li>
       <!--end repeating list item-->
</ul>

CSS

ul.column{
	width: 100%;
	padding: 0;
	margin: 10px 0;
	list-style: none;
}
ul.column li {
	float: left;
	width: 200px; /*Set default width*/
	padding: 0;
	margin: 5px 0;
	display: inline;
}
.block {
	height: 355px;
	font-size: 1em;
	margin-right: 10px; /*Creates the 10px gap between each column*/
	padding: 20px;
	background: #e3e1d5;
}
.block h2 {
	font-size: 1.8em;
}
.block img {
        /*Flexible image size with border*/
	width: 89%;  /*Took 1% off of the width to prevent IE6 bug*/
	padding: 5%;
	background:#fff;
	margin: 0 auto;
	display: block;
	-ms-interpolation-mode: bicubic; /*prevents image pixelation for IE 6/7 */
}

jQuery

function smartColumns() { //Create a function that calculates the smart columns

        //Reset column size to a 100% once view port has been adjusted
	$("ul.column").css({ 'width' : "100%"});

	var colWrap = $("ul.column").width(); //Get the width of row
	var colNum = Math.floor(colWrap / 200); //Find how many columns of 200px can fit per row / then round it down to a whole number
	var colFixed = Math.floor(colWrap / colNum); //Get the width of the row and divide it by the number of columns it can fit / then round it down to a whole number. This value will be the exact width of the re-adjusted column

	$("ul.column").css({ 'width' : colWrap}); //Set exact width of row in pixels instead of using % - Prevents cross-browser bugs that appear in certain view port resolutions.
	$("ul.column li").css({ 'width' : colFixed}); //Set exact width of the re-adjusted column	

}	

smartColumns();//Execute the function when page loads

$(window).resize(function () { //Each time the viewport is adjusted/resized, execute the function
	smartColumns();
});

Conclusion

I am planning on using this technique in the future, if anyone has any other ideas or techniques they use, please don’t hesitate to share it. If you have any questions, comments, or suggestion please let me know!

Did You Enjoy This Post?

subscribeSubscribe via RSS ,by email, or by twitter to get all upcoming
tutorials and articles delivered straight to you.

Bookmark or Share this Post!

  • Digg
  • del.icio.us
  • StumbleUpon
  • Technorati
  • Twitter
  • E-mail this story to a friend!

Tags: ,

This entry was posted on Monday, May 25th, 2009 at 9:15 pm and is filed under CSS/XHTML. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

106 Responses to “Smart Columns w/ CSS & jQuery”

  1. sonichtml

    Very creative, thanks to share ..

  2. Janko

    Interesting solution, I like new approaches. Good work!

  3. DefSol

    Very nice – thanks for the tip

  4. wink

    Now this is something I would definitely use! Awesome idea/solution.

  5. Patternhead

    Great technique and seems to degrade gracefully when javascript is turned off.

  6. Farooq

    Hi really nice and useful stuff its a good solution for the common problems for all web developers.

  7. Babatunde Adeyemi

    Lovely!

  8. Ruan Carlos

    beautiful, beautiful, beautiful, beautiful.

    No comments.

  9. Shane - Inspiring Your Success

    This is really interesting.. might have to find a use for it!

  10. Oxide

    Great article as usual. I was working on something similar but you get there first! :)

  11. Jônatan Fróes

    jQuery make things so easy….
    thanks

  12. v-render

    great info. thanks for sharing .. tweeting about it !

    http://www.twitter.com/veeroo18

  13. Nacho

    Great. I love it.
    Definetely very useful. Thank you :D

    Nacho

  14. Fred

    Hey that’s very nice.
    I saw a website wich use this kind of layout.
    http://skreen.it.twodecember.com/
    This works with Mootools, but it works perfectly.
    Take a look at it.
    Thanks.

  15. pplexr

    Amazing styling and great simple to use product,One of the best web app implementations I have have ever seen.

  16. Tutorial City

    Very smart! Maybe I’ll use this technique on my next project ;)

  17. Raymond Selda

    Very nice Soh. I love the design on your demo. This article will definitely be useful. Thanks.

  18. Supercharged

    Awesome. Would definately use it. Liquid images are also great!

  19. fernando trasviña

    hey cool article, i made a framework 6 months ago on this theory called elastic css framework

  20. Adam

    Perfect! I am working on something right now (just realized it was inspired by the ‘fancy thumbnail hover effect’ post from you a while back!!) that this technique will work perfectly for! I was going to go about it a different way, but this is slicker I think. I’ll post the results. Thanks Soh!

  21. pureelite

    Thats a great idea and the solution, as you posted is really simple! A must have.

  22. Tim Wright

    Very cool plugin! Another CSS3 property made possible by jQuery.

    PS. I love the design of this comment field!

  23. fernando trasviña

    I see an improvement with the smart columns, your current solution does Math.floor which leads to the following stack error:
    columns
    column

    column
    doing a Math.floor on every column will make a blank space column(realWidth%1) * column(n) pixels.

    This can be fixed with the next algorithm:

    Math.round(column(realWidth))
    column.last.css(width, parentWidth – sum(column:not(:last)(width)))

    the actual algorithm is implemented in the elastic css framework

  24. Lynde Roberts

    Thanks very much for this solution. I actually needed something like this for a project I’m working on at this moment. So it came at a good time!

    jQuery rocks!

  25. Christian Gehrke

    Oh, Your very clever and that looks very nice.

    Thanks for sharing.

  26. praveen

    *claps*. Nice technique. I’ll try to use it in my future websites.

    If this can be somehow integrated with the (fluid)960 grid system, it will be more helpful I guess.

  27. iFew

    oh.. great. thank

  28. Filipe

    Great blog, thanks for sharing this.

  29. neitz

    woow good solution slick design

  30. Gabe Harris

    Dang, that’s a sweet technique. Thanks!

  31. neitz2

    there is right margin!

  32. Aaron Smith

    Now thats what i call sexy! Fantastic, i love it!!!

  33. Eric E. Anderson

    Excellent write up – a beautifully simple approach to a complex problem. This would be a fantastic way to mark-up an e-commerce product list… *opens Coda*

  34. Annie

    Thank you so much for posting this. This gives me some ideas on how to create my own CSS-website.

  35. Euge Berzal - rulexdesign

    Great tutorial man, it’s very simple and help me remind me that method. thanks!

  36. Erik

    a link to download the code would be nice. I hate to type…

  37. Telly Koosis

    Where were you a couple months ago when I needed *exactly* this functionality?! :)

    Curious to know if you’ve tested performance when the block count dynamically changes? This was the problem I ran into. I have X blocks that display on init which I then allow to be filtered (show/hide) via jQuery. It’s functional for the most part but a bit inconsistent in some cases (ex. 1 row with 2-4 blocks visible). Still debugging but suspect my math is off.

    If interested: http://www.incalas.com
    Code (still in dev mode so bear with me): http://incalas.com/site_media/js/section/portfolio_grid.js

    Select a category > value to filter. For example, YEAR > 2007

    Regardless, a great solution that I’m exited to use if the filtration works. Thanks for this!

  38. Ariyo

    awesome tutorial, thanks for sharing.

  39. Faizal Amri

    youre Best tips and tricks… Hay Soh… I try youre simple page peel trick and thumbnail image and rotate image gallery… but its failed… can you give a tutorial with the example file maybe… Thank…

  40. J Mehmett

    Very creative solution, I like the idea, man.

    I was browsing Creative Depart (http://www.creativedepart.com/) on the other day, and I thought their columned layout solution.

    Your solution really rocks. I was designing an elastic (em based) layout for an upcoming project and I’ll think about this one if it fits the portfolio page.

  41. Andris

    Very nice technique. Thanx a lot for sharing your ideas.

  42. PB

    there is right margin!

  43. Razvan Pavel

    there’s a pure CSS way to do this,without the JS.

    if you have control of all the widths all you need to do is add an extra div around the the list and play with some widths and overflows

  44. 7skip

    really nice idea.

  45. Roberto

    Very nice. I’m definitely gonna try this. Thanks for sharing.

  46. Hezi

    this is rocknroll.

  47. Rich

    Very nice! I already see a ton of uses for this. Thanks for sharing!

  48. Harry Jennerway

    That’s pretty interesting. I know exactly where I can use it, cheers.

  49. Lachy Groom

    Hey – Can we get a download of this: http://www.sohtanaka.com/web-design/examples/smart-columns/?

    Cheers

  50. paulgiacherio

    This would be an excellent improvement for my Museum Theme. Nice work.

  51. Daniel H.

    Turned it into a plugin:

    (function($) {
    $.fn.smartColumns = function(options) {
    var opts = $.extend({}, $.fn.smartColumns.defaults, options);

    $(this).css({ 'width' : "100%"})

    var colWrap = $(this).width();
    var colNum = Math.floor(colWrap / opts.dimensions);
    var colFixed = Math.floor(colWrap / colNum);

    $(this).css({ 'width' : colWrap})
    $(this).children('li').css({ 'width' : colFixed});

    return $(this);
    };

    $.fn.smartColumns.defaults = {
    dimensions : 200
    };
    })(jQuery);

    Call it like this:
    $(’ul.column’).smartColumns();

    Or hand in the dimension:
    $(’ul.column’).smartColumns({ dimensions : 300 });

  52. Soh

    Daniel, thank you!

    You da man :-)

  53. Vitaly

    Really cool, thanks

  54. Diego

    Impressed O.O
    I was developing a similar project but I’ve never make it work right. Then I saw this post and it make my day!

    Thanks for share!!

  55. BigAB

    Came for the columns, found out about:

    -ms-interpolation-mode: bicubic;

    Thank you very much!

  56. Markdvl

    Fantastic Solution !!!!!

  57. Newbie

    Hi this is really helpful but if i want in detail What books would you recommend for beggining to learn css and javascript? Any suggestion would be appreciated.

  58. ZK@Web Marketing Blog

    Hi I’m using this plugin and it’s working very well except for one problem. It seems to be interfering with the jQuery ui dialog feature. When I include $.idleTimer(120000) in my script firebug shows a ‘too much recursion’ error when I attempt to close an open modal dialog. When I remove that line of code it works fine. Any ideas? Thanks in advance

  59. JONxBLAZE

    Thanks for posting this. Awesome idea!

  60. Martin

    Great idea. I have been looking for this type of solution for a couple of days. It is working well in my webpage.
    Thanks a lot.

  61. Poppy

    Will give this a try. Love it! Appreciate you sharing. Thanks.

  62. ramya

    but its not working in ie

  63. Avery

    Fantastic Solution !!!!!

  64. Web Designing Company New York

    Nice work…thanks for sharing this post.

  65. PaulD

    This is a beautiful solution.

    This has always been an issue for me, occurring on many sites. I usually end up having to contain the columns in a fixed size box, so small viewports have a scroll bar. A non-solution really, but that was what suited my situation the best – until now!!!!

    Can’t wait to try this out. Thank you,

    Paul.

    PS Great site, lovely design, keep up the fantastic work!

  66. PaulD

    @ramya

    ” …but its not working in ie…. ”

    YES IT DOES!!!!

    Paul.

  67. Calgary Graphic Design

    Something I have to try. Thank for improving my CSS chops!

  68. BenDesign

    Great Code. Thank you. I definitely try this next time i create columns…

  69. Jason

    Very nice as always Soh, but is there a way to do this with fixed column size instead of liquid. Just want the space between divs to equalize when the browser window size changes. Thanks for the great ideas!

  70. kidotch

    これは最高にクールですね
    是非参考にさせていただきます

  71. Adardesign

    Nice, Thanks.

    1 comment:
    in the CSS i found “width: 89%; to prevent IE6 bug”
    i am not sure deserves such a global recognition, you could of styling IE6 with width:90%; _width:89%;

    Anyway,
    Thanks

  72. Misty Beier

    Great tutorial! This is perfect for a photography portfolio!

  73. Darkimmortal

    I, for one, prefer the fixed sizes. Looks more natural.

  74. Vic

    very interesting tutorial, thanks!
    quick question: I’m trying to integrate the page with lightbox, but it seem that the page load either the resize or the lightbox, but never together
    Suggestions?

    thanx!

  75. Abin

    Thanks for sharing…

  76. R

    Thanks a lot for this tutorial. Really smart and useful technique. I have released a wordpress theme based on this tutorial at http://premiumthemes.net/news/snippet-magazine-wordress-theme-with-smart-flexi-columns.html

    thanks

  77. Emko

    Thank you so much. It’s so creative and inspiring!..

  78. Tony

    Has a anyone seen what happens when the browser window is only big enough to display two or even one column? It stretches them out to fill the space. Has anyone found a fix or workaround or something for that part? Otherwise this is very nice.

  79. eddie

    greate!
    but why it doesnt work when I remove the “container” div?

  80. neel

    Excellent article. I always have this kind of problem when i want to show some thumbnail images. Now I have a solution to use in future projects.

  81. Claudia

    Thanks so much for making this available. It’s made things very easy for me to display book covers in nice, neat columns.

  82. realest

    I added columns on my site http://slo-novice.com and when i open a lot of tabs in firefox and not looking the loading of the current site, sometimes columns doesn`t stretch :\
    And yeah content is dynamic.

  83. Andrew

    Is it possible to include funtionality to specify the number of rows you wish to have?

    If I have 12 items at 100px wide each, and my browser is only 500px wide, how can I display 1 row with 5 items? If I resize my browser to 800px wide, how can I show the additional 3 in the row?

    If I want to have 2 rows, and my browser is only 500px wide, how can I limit the 12 item list to 10 items or 5 on each row?

  84. Eric Lightbody

    Friggen brilliant. Thanks for sharing!

  85. sophy

    Create tutorial, Thanks I like this

  86. 병진

    감사합니다.

  87. Projektowanie Stron Internetowych

    So creative and inspiring, Thank you

  88. Manny

    you are a genius, thanks for show us this. [",] manny

  89. Bowenkämper

    This is a short, simple, but wonderful technique!

    Thx for sharing!

  90. Akhil

    its creative and useful solutions ….. i like it

  91. Andy

    One option would be to add a timeout to the resize event so that the javascript doesn’t fire with each delta in the resolution (only after the user has stopped resizing for say 400ms). It *could* help from overloading the browser with js processes on ones that have high resolutions on their resize events. Although I’m not sure how that display would look in the meantime before the smartColumns() fires. Hmmm.

  92. lara

    Hi!

    Loved this article and also the page design ;)

    I’ve been recently develloping a website, on witch earh results are presented to fit on the screen… So, have a with floating ’s inside. So, instead of changing the items’s width with the remaining space, i splitt that space in two, and turned it into left/right margin. The gets centered, and it’s width is calculated based on how many items fit on the screen. The function needs to be called on $(document).ready() and also on $(document).resize()

  93. Görkem

    Excellent, thank you.

  94. Symon

    Genius. Thanks for the inspiration!

  95. Arlequin

    Wow ! Love simple trick for definitivly GREAT EFFECT … Thùnks!! (I know it’s not a «ù» but sounds funny and looks funny!

    Arlequin

  96. Kabamaru Igano

    Thank you for the knowledge :)

  97. OrbitDesign

    Great Code,
    Thank you :)

  98. younes

    can you send to me the source file pliiiz
    because i dont know haw i creat this
    pliiz

  99. Matt Lewis

    Love this, very awesome for liquid layout design. Pulled the demo up on my iPhone and was hoping to see things resize for the dimension restraints, but I still see a page 4 columns wide. Was hoping it might be smart enough to go 1 column wide due to the size of the screen.

  100. mrak911

    It’s so creative and inspiring!..

  101. 波波

    额,支持中文发言不?我试试

  102. Neil

    Very nice, looks great love your blog. I’ve seen something similar to this done with comments on a blog and they had a tutorial on it, anyone happen to know the blog I’m talking about? I saw it a few months ago and didn’t bookmark and can’t find it. Thanks.

  103. Neil

    I’m so sorry I just found the webpage a few minutes after I posted that (after hours of searching previously) http://digitalmash.com/journal/articles/dynamic-columns/ :(

  104. seo

    thanx perfect div css :)

  105. Projektowanie stron Toruń

    Great. I will use it on our websites

  106. Ryan Foster

    Thanks for the awesome tutorial. I generally code with Prototype as my first preference, so I turned it into a Prototype Class:
    http://www.hotwaxmedia.com/apache-ofbiz-blog/prototype-tutorials-smart-columns/

Speak Your Mind…

Need to post HTML code?
Use Postable for your convenience.

Don't have an Avatar?
Set up a Gravatar image now!

Blog Blog Categories

Popular Comments Popular Posts

Recent Comments Recent Comments