ternstyle - Lehigh Valley, Allentown, Bethlehem, Easton, WordPress, Lehigh Valley web design, web programming, web development, lehigh valley web hosting, content management tools, website plugins, WordPress plugins, WordPress Themes, php libraries, php classes, javascript libraries, javascript classes, jQuery plugins, web programming, free web software, free php classes, free software

  • NEW EVENT PLUGIN FOR WordPress ™!

    ternCal is the New Ultimate WordPress ™ Event System!

    Featuring repeating events, Google Calendar integration, ICAL and Outlook Support, month, week, and day views, WordPress ™ short code for listing events, a color coded legend and much much more...

    Check it out now!

Float vs. Inline-Block

This is an interesting topic for me as a web designer who is also a programmer. My mind is almost always geared toward efficiency in my work which draws me to the question which is most efficient; floating elements or making them inline and block level. I suppose these are not our only options but these are the two main methods I’ve employed when rendering my designs so these are the two I’ll write about.

Both of these methods have their flaws and quirks which present themselves uniquely in different browsers. Aside from efficiency we’ll also have to take into consideration browser compatibility. These are the two standpoints from which I’ll explore the two very contrasting methodologies.

The Float

The first thing we should know about floating elements is why this method was invented in the first place. The original concept of the float was for text-wrapping. The idea was to take a block level element, such as an image, and set it to justify to the left or right respectively while allowing text to wrap around it. Its application, although very effective as a means for rendering an entire document of elements, is a bastardization of its original intention. You say, “Who cares?” Well, as a result of the aforementioned bastardization there are precautions that must be taken to make sure that a page is rendered properly visually when using floats this way.

The main issue presented by floating elements is that a floated element is not automatically recognized by its containing parent element. In my opinion this was a flaw in its application from the get-go. Regardless as to the element being floated its parent element’s size should change accordingly to accommodate the floated element. It does not (without some trickery).

The second and daunting issue with floats is that you can’t center floated items. So if you have a list where you’d like the items centered in your document and you’ve floated the list’s items you’d need to set a width to the list to be able to center it properly. This means no more purely dynamic list. Whenever you add or subtract an item you’ll need to update the width of the list to make sure it stays centered. For this I don’t like floats for anything centered.

Notice below that the parent element with a 3 pixel border does not properly resize to envelope its child which is 200 pixel in height.

This is a floated element which is floated to the left and has a parent element with a 3 pixel border.

 

The float everything method

This method is fairly self explanatory. For some reason a  floated parent recognizes the size of its children who are also floated. I find this to be a weak option but one I employed myself for quite some time. Look back at some of my old sites and have a giggle. This method requires making sure most of your elements are floated which means a lot more CSS. I recommend against this method. One of its main issues is the addition of plugins or add-ons which use their own CSS or the minute styling details you’ll need to delve into when adding things inline with content. And don’t get me started on how fun this becomes when your talking about forms and form elements and how poorly they’ll begin to play with others. Move on from this method.

The clear fix

The “clear fix” is probably the most widely used solution to the float issue and is being employed in the above example to ensure that this text does not sit directly under the seemingly empty parent container. CSS has a command entitled “clear”. The clear command when applied to an element forces that element to be rendered under floated elements which float matching the associated value. The above example uses the command “clear:left;”. This command will make the element it is applied to clear any element rendered in its path that is floated to the left. Other values include “right”,”none” and “both”.

The clear fix is clunky. You need extra html mark-up placed in your code wherever something is floated. It’s just plain inelegant but it works. The following code does the trick:

<div class="non-floated-parent">
     <div class="floated-child">
          This is a floated element which is floated to the
          left and has a parent element with a 3 pixel border.
     </div>
     <br style="clear: left;" />
</div>

The overflow method

The overflow method is the most elegant solution. It’s pure CSS. There is no need for extra mark-up. No need to alter your templates or HTML. However, you still need to add a few lines of CSS to any element which is not floated and has floated children. This method consists of adding a CSS width and overflow attribute to the containing element. Like so:

.parent {
     overflow:hidden;
     width:100%
     border:3px solid #333;
}

The child can then be set up like so:

.child {
     float:left;
     width:200px;
     height:200px;
     background:#ccc;
}

The above code will produce this:

This is a floated element which is floated to the left and has a parent element with a 3 pixel border.

This method requires a minimum of one CSS command be applied to each or a group of parent element(s). I like this one the best so far in terms of floating elements.

Articles to read on floats:

The Inline-Block

The inline-block method is just as quirky (maybe quirkier) as the float method and requires its own work-arounds. Firstly, Internet Explorer 7.x and earlier does not care to treat an inline-block element as an inline element. It only assigns it block level status. This means that just like a block level element inline-blocks are rendered on their own lines regardless as to the space they consume on the horizontal plain. This requires you to use conditional CSS commands to reset anything set as an inline-block which needs to actually be rendered inline as simply “inline”.

Also, vertical alignment at times becomes an issue with inline-blocks. So you’ll need to account for this by using the CSS command “vertical-align”. Lastly and probably the most daunting issue with inline-blocks is that when they align themselves they recognize whitespace such as a carriage return or a tab character in the actual html mark-up as an inline element and depending on your font-size (because yes your font-sizes are applied to whitespace) you’ll see space between things like list elements which you’re attempting to render on one line butted up against each other. There are solutions for all of these things.

Here is a menu styled using the inline block method:

  • List Item 1
  • List Item 2
  • List Item 3

Notice that if you’re using IE 7 or earlier the list items are rendered on their own lines. If you’re not using IE7 or earlier but wish to see what it would look like, it looks like this:

  • List Item 1
  • List Item 2
  • List Item 3

The IE 7.x and earlier issue

The way I resolve this is with conditional stylesheets. You can read about that here: http://css-tricks.com/how-to-create-an-ie-only-stylesheet/.

More often than not I am using the float or inline-block element for either my columns or my navigational lists. Here is the code I would use for my lists for all non-IE7 and earlier browsers:

ul, li { display:inline-block;margin:0;padding:0;list-style:none; }

This will set up your lists nicely for you to style them individually throughout your pages. Here is what the CSS should look like in your conditional style-sheet:

ul, li { display:inline; }

Thats all you need to fix the IE 7.x and earlier issue. I use conditional stylesheets anyway because I prefer to use CSS for my png’s over javascript.

The Vertical Alignment Issue

Take a look at this menu with mixed heights:

  • List Item 1
  • List Item 2
  • List Item 3

Notice that the vertical plane the items are rendered in is set by the text inside the list items. The text is rendered inline with all the other text. This is an issue when setting up columns in a document as inline-blocks. You can float three divs next to each other and they’ll be rendered with the very tops of themselves as high as they’re able to go. This is not so with inline-blocks. With inline-blocks the text is respected more so than the containing element.

To fix this I use this code:

ul, li { vertical-align:top; }

Or so that I don’t need to set this multiple times for all elements which require it I’ll use this command which set everything to be aligned this way:

* { vertical-align:top; }

This code will make the above menu look like this:

  • List Item 1
  • List Item 2
  • List Item 3

You like? Well we still have the pesky space between the items to deal with.

The Spacing Issue

This one is no fun at all and may make you abandon the inline-block method and stick to the float method. I’m okay with that. Do what you’re comfortable with.

Okay, let’s remember that the issue at hand is the recognition of the whitespace characters like carriage returns and tabs in your actual mark-up between your elements you’re attempting to block together. The first thing you could do is simply remove the whitespace.

Our menu to be easily readable and editable looks like this:

<ul>
     <li>List Item 1</li>
     <li>List Item 2</li>
     <li>List Item 3</li>
</ul>

To alleviate this issue right away we can write the code like this:

<ul><li>List Item 1</li><li>List Item 2</li><li>List Item 3</li></ul>

See below for what happens when you remove the whitespace:

  • List Item 1
  • List Item 2
  • List Item 3

Nice! With one major exception. We can’t always do this. If you’re using a content management system or any code that renders certain aspects of your HTML for you you may not be able to effectively remove all that whitespace. Now what?

Well, remember your browser sees that whitespace as text so it is assigning a font-size to it. Let’s see what happens when we set the ul’s font-size to zero:

  • List Item 1
  • List Item 2
  • List Item 3

That works great! Except now we are unable to see the text inside the list items. So If we want to set the font-size to zero we need to do this to the parent element (the ul) and then reset the text of the list items back to what we want them to be. That’s a lot more CSS if we weren’t already specifying the font-size for the list items or any links they may parent. This method, although effective, sucks! If you’re using inline-blocks though it may become necessary.

There are some other tactics to circumvent the spacing issue like setting negative margins. The best way is to remove the whitespace. If you can’t do that it’ll take a few font-size command to set you straight.

Articles to read on Inline-Blocks

Float vs. Inline-block Chart

Method Issues Solvable
Float Not entirely
Clear Yes
Can’t center floats Not really but yes depending on your definition
Inline-block Yes
IE 7.x and earlier Yes
Vertical align Yes
Whitespace Yes but it can get clunky at times

In Summary

Each method has its own symptoms and repercussions. There are solutions to all the problems that both of these methods produce. Some of the solutions are actual solutions and others are work arounds. It seems to make the most sense to not adhere strongly to one method and use them in situations that call for them. How do you know which situation calls for which method? Use the one where you can employ actual pure CSS solutions instead of work arounds. Don’t lose the dynamics of your pages by having to update the CSS every time you need to make a change.

For instance, I’ll use floats for images (their original intention) and when dealing with areas of pages with fixed heights. A fixed height means no need for a clear fix. I’ll use inline-blocks for template columns. Columns are a part of the template that aren’t usually dynamically driven so it’s easy to remove whitespace between the column elements. For menus and navigation inline-blocks work great for vertically aligned lists and with the vertical-align and font-size fixes are great for horizontal menus that are center aligned. Usually horizontal navigation has a fixed height so floats are okay. However, and a big however, if you’re dynamically generating your horizontal menus and floating the items right they’ll be rendered in reverse order. In which case, I’ll usually use inline-blocks for right justified horizontal navigation or really any navigation where I don’t care if there is a little space between the elements.

First and foremost, write efficient compact code in whatever way makes you happy, comfortable or suits your compulsions. I know I do. Happy codings.

Home > Blog > Float vs. Inline-Block

  • http://elementmedia.us Marty

    This has to be one of the most in depth descriptions of Float vs. Inline that I have ever read… very well presented sir. I do agree that floats can get quite messy at times… i’ll be sure to use your article as a reference point in the future.

    • http://www.ternstyle.us admin

      Marty, thank you for your response. It is always appreciated. Pass this one on if you can. I know this is often an issue for developers who attempt cross-browser compatibility. I hope you are well.

  • http://www.scheetzdesigns.com/ Justin Scheetz

    Great article! I’ve always switched back and forth with these and find them both to hold the same amount of frustration at first. Once you understand how the IE’s handle these elements (by reading articles like this), it’s a pretty quick fix.

    Another thing to possibly note here is the float/margin issue. When you float something and add margin to it, it doubles that margin in IE6. The easy fix? Add “display:inline;” to the element. The better fix? Don’t use margins at all—just add padding to its parent element.

    • http://www.ternstyle.us admin

      That is a great point! I’ve had to deal with that issue countless times. At times I use padding and if I really want it to be a margin (in times where I have a width set on the parent element) I usually go halfsies on the margins in my conditional IE6 sheet.

      Thanks so much for the comment.

  • http://www.digital-results.com/ Russell Bishop

    Excellent write up with brilliantly balanced arguments. I’m quite content just floating elements and clear fixing the parent – the only problem this ever seems to lead to is odd bottom margins on footers.

    Thanks!

    • http://www.ternstyle.us admin

      Russel, thank you for your comment. It’s always interesting to me to get various perspectives on how people work their CSS. I floated exclusively for a long time and now mix the two methods for optimum effect respectively.

  • http://belajarsendiri.com Cara Membuat

    Thanks for this tutorial. I am a newbie in dreamweaver, I usually use ‘float’ but now I know the uses of ‘inline-block’. I’ll recommend this blog to others

    • http://www.ternstyle.us admin

      Cara, You’re welcome. Glad I could help. Thanks for passing this article along.

  • http://www.telephonesystemsdirect.co.uk Telephone Systems

    I have just forwarded this link to my web designer as there is no way that I would have been able to articulate it to him better than you have done in your article. I will telephone him tomorrow as I like to text to wrap around images for that look on our sites. Bravo … you just helped a small business.

    • http://www.ternstyle.us admin

      My pleasure.

  • http://www.nousinfosystems.com Charas

    It is very clear and good explanation with screen shots it will very useful for the newbies. I will be sending this link to my new designers.

  • http://www.mightytemplate.com/ Best Joomla templates

    I wish all blog posts all over the web were as informative and useful as this one. Great job you did describing this issue. Well done. It worth a tweet from me :)
    I never used to work with web design so closely. I usually use float and never used inlines. But now when I get back to studying CSS I know the exact place to visit to learn more about this subject.
    Thank you for work you did for all of us.

  • http://www.20milesnorth.com Spokane Web Designer

    You made some very good points about floating div’s and solid ways to correct them. That whitespace issue on elements in IE has kept many designers up late nights scanning their code wondering what was wrong.

  • http://ericportfolio.com Eric porter

    Extremely concise, thx a bunch.

    “In which case, I’ll usually use inline-blocks for right justified horizontal navigation”

    -Been looking for an answer to that. Hat’s off, friend.

    • http://www.ternstyle.us admin

      Glad I could be of assistance.

  • http://jbuc.com Jacob

    Thank you very much for this post. I think all in all (like most layout techniques) they both shine in their own regard and for their own specific situations (as you pointed out).

    But, that being said I think that the inline-block method should be at least written about more. Perhaps I have just been thick but I don’t think I’ve seen it used much at all, and maybe it’s because of the white-space issue, but I also think its infrequency is also due to obscurity.

    All that aside though – I wanted to point out how yahoo seems to be handling the whitespace issue (this is the method they are using for their grid v3).

    for the elements that are being rendered inline-block they have set the following properties:

    display:inline-block;
    zoom:1;
    *display:inline;
    letter-spacing:normal;
    word-spacing:normal;
    vertical-align:top;

    things to note in this:
    1. the *hack is being used to slice out the ie rendering like you did in the conditional stylesheet. (either or, do what you like)
    2. zoom:1 fixes some display issue I think with the way ie7 handles the display:inline (regardless, the display:inline + zoom:1 make this thing work in ie7)
    3. the word-spacing and letter-spacing are to reverse the next thing they are doing which directly addresses your white-space concern.

    The following styles are applied to the parent of the inline elements in question (in your example, the ul):

    letter-spacing:-0.31em;
    *letter-spacing:normal;
    word-spacing:-0.43em;

    I haven’t fully fleshed out this whole thing but it seems to handle the white-space issue you described. Anyway, I think at the least it’s worth further investigation. Thanks again for the post.

    • http://www.ternstyle.us admin

      Jacob,

      Wow. Great work. Thanks for this post and for doing the research.

      I like the zoom technique and the IE 6 hack saves an HTTP request by eliminating the conditional stylesheet as long as it isn’t needed otherwise. (I use the conditional stylesheets as a matter of preference. I try to only use CSS hacks at this point in my back-end design where functionality matters more than aesthetics and compliance.)

      I have to say, I’m not a huge fan of the negative word-space and letter-spacing. Granted, it’s a similar amount of CSS commands but what if a browser’s default letter and word spacing differs from the one you choose to offset. Setting the font-size to zero, I think is fool proof and cross-browser compatible.

  • http://twizzlebird.co.uk Dave Wright

    I have always used a clear fix div class, I wasn’t aware of the overflow:hidden technique however, this seems much cleaner, you’ve converted me!

  • http://www.facebook.com/rcambridge.co.uk Robert Cambridge

    overflow:hidden has it’s consequences (any non-floated child elements outside of the parent’s visible area will not expand the box).

    The default is overflow: visible.

    Use overflow: auto :)

  • Larseirik

    Great article. Makes it easier for me as a developer to understand the whoe css layout issues.

  • Dinesh Ramakrishnan

    Great article… this addresses many confusions between float and in-line block usages.

  • http://www.facebook.com/profile.php?id=100002695029441 Richard Walton

    Great article. Answered all of my questions.
    I think I’ll be sticking with floats, for the most part.

    • Anonymous

      Once IE 6 and 7 become obsolete inline-blocks should become more prevalent than floats.

  • Myke

    probably one of the most informative posts i’ve ever read about floats and display-inline. Thank you SOOOO much for this article.

  • Thomas Kettner

    Great Article! Not only from a technical perspective but also easy to read and perfectly stressed.
    Thanks for that.

  • Detlev Kemps

    Definitely useful. Regarding IE6 and IE7, I would recommend to any developers to ignore it. Why? Because IE7 is from 2006 and IE6 from 2001. The percentage of people currently using it consists out of developers for testing purposes. The real consumer world does not use it anymore, period.

    • Micah Mutrux

      In general I also feel good about anything I can do to help rid the web of IE 6/7.  But the war isn’t over yet.  Yes, both versions have single digit percentage shares of overall usage, but there are still some concentrated pockets.  In a recent project I did for a company that provides public insurance comparisons we found that 80% of their visitors are still using XP and IE 7 or 8.  

    • Jerem

       The best way to help them to update their browsers is not coding anymore for them. If most of the websites they visit do not display well, they will wonder about it.

  • Ben Miller

    cheers! was getting really ****ed off with my divs ignoring thier floating children!

  • Adriano Martino

    Well, for the moment it’s better to use floats without adding conditionals. In the future it’s good to use both. One difference is that with the float you can actually have an element before in the markup and put it after with a float right. That is a feature that the inline-block does not offer. As for the height especially for menus I use line-height.

  • Emma

    Great post! For a long time I have been wondering how to get around the clear:both; issue. And all this time all I needed to do was set overflow hidden on the parent container :) Thanks again!

  • Christopher Errey

    Great article, the font-size:0 and the vertical-align:top; a real life saver.
    Thanks again.

    • ternstyle

      You’re welcome Christopher. Glad it was a help to you.

  • http://www.facebook.com/profile.php?id=1074713431 Adam Richardson

    Great post thankyou :)

  • Fernando Santos

    Finally a great article about this issue. It cleared my doubts and helped me a lot with my templates and I don`t need anymore to use “bad codes” in order to solve the problems…. Sorry about my English, because it`s not my official language. I speak Portuguese.

Copyright © 2010 Ternstyle Inc. All rights reserved.
site design: ternstyle.us
Lehigh Valley Website Design