I’ve seen this come up a couple of times lately on Twitter and then an interesting Dabblet so I figured it would be an important thing to document.
Here’s the deal: a series of inline-block
elements formatted like you normally format HTML will have spaces in between them.
In other words:
<nav>
<a href="#">One</a>
<a href="#">Two</a>
<a href="#">Three</a>
</nav>
nav a {
display: inline-block;
padding: 5px;
background: red;
}
Will result in:
We often want the elements to butt up against each other. In the case of navigation, that means it avoids the awkward little unclickable gaps.
This isn’t a “bug” (I don’t think). It’s just the way setting elements on a line works. You want spaces between words that you type to be spaces right? The spaces between these blocks are just like spaces between words. That’s not to say the spec couldn’t be updated to say that spaces between inline-block elements should be nothing, but I’m fairly certain that is a huge can of worms that is unlikely to ever happen.
Here’s some ways to fight the gap and get inline-block elements sitting directly next to each other.
Remove the spaces
The reason you get the spaces is because, well, you have spaces between the elements (a line break and a few tabs counts as a space, just to be clear). Minimized HTML will solve this problem, or one of these tricks:
<ul>
<li>
one</li><li>
two</li><li>
three</li>
</ul>
or
<ul>
<li>one</li
><li>two</li
><li>three</li>
</ul>
or with comments…
<ul>
<li>one</li><!--
--><li>two</li><!--
--><li>three</li>
</ul>
They’re all pretty funky, but it does the trick.
Negative margin
You can scoot the elements back into place with negative 4px of margin (may need to be adjusted based on font size of parent). Apparently this is problematic in older IE (6 & 7), but if you don’t care about those browsers at least you can keep the code formatting clean.
nav a {
display: inline-block;
margin-right: -4px;
}
Skip the closing tag
HTML5 doesn’t care anyway. Although you gotta admit, it feels weird.
<ul>
<li>one
<li>two
<li>three
</ul>
Set the font size to zero
A space that has zero font-size
is… zero width.
nav {
font-size: 0;
}
nav a {
font-size: 16px;
}
Pre-Jellybean does not remove the space at all, and Jellybean has a bug whereby the last element randomly has a tiny bit of space.See research.
font-size
to bump it back up.
Just float them instead
Maybe they don’t need to be inline-block at all, maybe they can just be floated one way or another. That allows you to set their width and height and padding and stuff. You just can’t center them like you can by text-align: center;
the parent of inline-block
elements. Well… you kinda can but it’s weird.
Just use flexbox instead
If the browser support is acceptable to you and what you need out of inline-block is centering, you could use flexbox. They aren’t exactly interchangeable layout models or anything, but you might get what you need out of it.
See
Example on CodePen:
I always use the negative margin method, but the floating method, simple as it is, will be of great help to me.
me too, negative margins.. cool, thanks.
@Landis and @Julian: You guys may want to reconsider the negative margin technique. Here’s an example as to why. It’s best to use designs that are not dependent on zero white-space. If you have to, use the comment method or don’t use carriage returns between elements.
Using negative margin too, think that’s best because you are actually adjusting the elements position. Using left: -5px; might be a good idea, but of course that brings all kinds of scary risks with it.
use all li’s in one line then the magical margin will not appear , actually the margin comes when you write the html code and do enter after each li the new line makes the magical margin
Thanks
Shaban Khan
UI/UX Engineer
Same here… always negative margin.
That 0px font-size trick looks pretty cool…
Leaving off closing tags is like running across the beach naked. The horra! I use the negative margin too
I dont know running across the beach naked could be interesting
I too have always used the negative margin method, I might start using the font-size technique however – just seems too simple to give it a miss.
Negative margin has always been the way I’ve gone – it maintains semantics, code structure and keeps the ‘fix’ directly associated with the object.
All of the other techniques either toy with the underlying code or create an association that I (or another developer using my code) would need to be mindful of.
The YUI 3 CSS Grids use
letter-spacing
andword-spacing
on their grid container to collapse white-space between the grid units.http://yui.yahooapis.com/3.5.0/build/cssgrids/grids.css
I use this trick as well, and I’ve found it to be the best by far.
font-size: 0
is a completely unusable solution if you want to useems
or%
in any of your child elements. It also doesn’t work in Safari 5.0.Floats aren’t ideal either as they mess up the vertical baseline when trying to align inline-block elements of different line-heights. Also, you have to clear them.
Bootstrap has the same things may be. And it work great…
No, bootstrap uses floats
This bugs in Firefox in floats, so better separate letter-spacing to Webkit-only browsers.
P.S.: I’ve submited bugreport to webkit bugzilla in September 2011. I hope they’ll fix it eventually.
This solution isn’t bulletproof because it counts on three assumptions: the width of the space equal to 0.31em (nearly true for Arial/Helvetica, but false for Times New Roman etc.), the limit for the negative word-spacing that prevents words from overlapping (true for FF and IE8+, almost true for Opera, but false for WebKit and IE7-) and the WebKit bug that word-spacing is completely ignored for inline-blocks. When this bug is fixed, the inline-blocks will be “squeezed” a bit because the word-spacing is too big and the second assumption falis in WebKit.
Just saying… I have used the YUI grid system for over a year now and have had no problems. I have tested about every grid system out there, and the YUI one takes the cup for being both light weight, bullet proof, and responsive (with modification). Here’s my version… for responsive layouts… with shorthand… converted to a common denominator. Basically, you can omit the”yui-3-” part of the class names, and grid units are “base 24” as such: .u-4-24, .u-6-24, .u-18-24, etc… or you can still use yahoo’s original names if you like using calculators.
We can also use ” word-spacing : -4px ; ” on the parent element; works just like putting the negative margin on the li elements does.
Sreejesh KV, such a sollution is definitely better than a negative margin :) Especially when the elements need to be alined left where the negative-margin method would shift the first list item too.
The way I used to handle it is not to apply the shift for the first element via the
:first-child
selector.Floating, suggested by many people here, makes the elements block-level, they are not inline-blocks anymore then). That’s cheating)))
Yes, you are right. That is why I prefer the ‘word-spacing’ method.
Ya, this is the ticket. Nice work.
If its a Nav, just float the darn things. At least that works in all browsers and doesn’t resort to crazy font-size hacks, or unholy open tags, etc. Maybe I’m just old fashioned…
Exactly what I was going to say.
The only way that I know of to do centered navigation (without knowing the final width) is to use
ul { text-align: center; }
andli { display: inline-block; }
So tricks like this are very necessary.
Great tip, I also use the negative margin technique
I always use the floating method. On that way you got the absolute control over your HTML.
I use float because all the tutorials on making a nav bar I every found used float and it’s simple and makes sense. I wasn’t even aware there were other ways and thought float was the right way to do it.
It’s interesting to see other options for when I’m working with someone else’s code and they did it one of the other ways.
I just don’t like the idea of leaving out closing tags and am not looking forward to working with code where they are left out just because they can be. I don’t put those closing tags in there for the browser, they are for me when I’m reading the code :-)
So the issue is called “bike shedding” and in CSS3 there will be a property to fix this as the spec calls for. So what it comes down to, as Chris said, is the space between elements. So you could do:
<ul><li>one</li><li>two</li><li>three</li></ul>
but that makes the code really unmanageable. My findings led me to what Geert De Deckere posted as the best way to solve the problem.
As far as I know, this property has been renamed to “white-space-collapse”
Negative margin breaks here (Firefox 13 on linux)
Still one pixel of whitespace is between the elements.
(What did you decide that a space would be exactly 4px in my font?)
I’m seeing the same thing on Firefox 11 on Linux.
The negative margin method is *incredibly* unreliable: the -4px is only appropriate for one specific font size on one system. Using an em value seems to works across systems, though I forget the exact value right now…
Awesome article..i came across that type of list but didnt knew the reason..now i know :) hope u wont mind if i write this trick up in my blog..Not to mention, i will have a back link to this post ;) awesome stuff
Thanks for your explanation. I’ve met this problem quite often, but haven’t found any article saying about this, until now. I do float the elements, it works, but other solutions mentioned in this article sounds great, too.
Thanks.
I use float instead of inline-block, and for exactly the same reasons as Daniel and ian do. Why make things more complicated than they need to be?
But, great workarounds nonetheless for those that need them!
When I’m sticking a bunch of stuff on the same line, I usually stick the code on the same line also. It might not be as semantic technically, but it suits my thinking style.
As long as my links aren’t too long, it remains fairly easy to read, but it also solves the spaces issue, and since it’s going to display horizontally anyway, I actually kind of PREFER writing it out horizontally. Maybe I’m just weird like that.
Nice post, Chris.
I have had great success in the past with the
font-size: 0;
on the parentul
and the proper font size set on theli
. I only use this when the list items need to be centered though. I use floated blocks for everything else.For those of you who say you just use floats, how do you handle centering a variable number of variable width blocks? Inline-blocks are just so convenient for that, but if there is a way I can do it with floats, I’d love to know how.
How about setting the UL to inline-block, and text-align center on its parent, and then floating LIs inside the UL?
nav {
width: 100%;
text-align: center;
}
ul {
display: inline-block;
}
li { float: left; }
foo
bar
Here it is in a JSFiddle:
http://jsfiddle.net/kpadx/
thats a lot better than my solution
http://jsfiddle.net/kpadx/27/
That method looks great, Tom!
I think setting the font size to 0 is the optimal solution here, and also the cleanest.
Unfortunately there’s an issue with Safari for windows where font-size:0 is not respected for whitespace, rendering the otherwise easiest solution of setting font-size on the parent element
Css would be
This works as long as you don’t care about support for Windows safari and will be supported in all other versions of browsers currently supported inline-block.
Correct methood is removal of whitespace in the html markup at whatever methood you feel looks best.
I prefer:
I can’t say that I know any good standards for removing whitespace in code, so I wouldn’t say this is right or wrong.
As this is not a bug but the browswers rendering block elements as if they were inline they are correctly interpreting the whitespace in the code.
wow and lol this post gets a lot of attention. 100 email notifications in my inbox. You get a smiley. :-)
thanks for the great writeup!
the idea of leaving off the tag has been around since 2008…
http://meiert.com/en/blog/20080601/optional-tags-in-html-4/
Paul Irish brings it up here more recently…
http://paulirish.com/2011/primitives-html5-video/
after 15 years of obsessively closing everything in sight, the idea of omitting the closing tag made be feel a bit queasy :) that subsides quickly.
for me, less code is better. AND it also works all the way back to IE6.
that said, do what makes you and your team happiest.
From my experience this works pretty well cross-browser without having to set an absolute pixel font-size:
I used this technique in an inline-block layout demo on jsfiddle
I’ve used the negative margin, but seeing as it breaks in IE 6 & 7 and can pose problems with things off to its right.
The font-size looks cool and probably non-breaking.
this is beautiful thank you so much
I’ve always floated elements to remove the whitespace personally, though if this has been infeasible for some reason… I irritate my pedanticism and simply place all the LI tags on one long line, HTML comments seems to be a better method.
I’d always wondered how others worked with this “bug”.
Done too much style support for IE6 wayback so never got acquianted with inline-block. Float all the way and static master blocks (header/nav/footer) always onelined/minified.
Also: with html comments watch out for the duplicate char bug http://www.positioniseverything.net/explorer/dup-characters.html
Those were the days!
Thanks for documenting this, Chris.
I’ve poked a bit with
display: table
and came up with a solution for fixin this as you can see here.Basically you define
display: table
on the parent element (in your first example this isnav
). If you want to align the children centered you need to define a width for the parent element which is not possible in every case.Maybe this comes in handy some time.
Pete B, your idea is definitely worth a try!
It’s funny, I’ve been using the inline-block method exclusively for many many years, and rarely do I worry about the white-space issue. I just don’t design layouts that rely on zero space between elements.
When I do have to worry about it, I either use the comment method or just not have a carriage return between the elements. Either way, the fix is so much easier than everyone is making it out.
I stay away from all CSS methods because of browser inconsistencies. I’m also not sure if Chrome allows for zero font-size, at least it didn’t use to allow it. The negative margin should also present problems because not all browsers calculate the white-space exactly the same.
In my opinion, from using inline-block for so long, is avoid designs that are dependent on zero white-space (it’s easier than you think) or just use the comment method or no carriage return.
I also think it’s better to use the HTML way (no carriage return or HTML comments) because every CSS method rely on browser inconsistencies, which is as we know, not very reliable.
Though I never been faced to such a problem, but I guess I’d use the no carriage way. Seems the less tricky.
Negative margin method is not pixel-perfect by nature.
Floats are limited (cannot be line-wrapped like inline elements as well as easily centered).
Comments are littering and causing troubles in IE7 as for :first-child pseudoclass and adjacent-sibling combinator (there is a JS workaround though).
Omitting closing tags is somewhat nonsemantical and therefore unsuitable for some perfectionists (like me ;-).
Zero font-size trick is probably most practical currently. By the way, when using it, it makes sense to use `rem`-unit font-size for child elements to keep layout em-aware. `rem` means font-size of document’s root element (`html` element in case of HTML document), and the unit is supported by current versions of all browsers (incl. IE9). Pixel font-size value can be used simultaneously (before `rem`-unit value) as a fallback for older browsers:
It is 100% semantically equivalent to putting closing tags directly before the next sibling’s opening tag or the parent’s closing tag. It results in the same DOM tree (with no text nodes between items). Of cours the first option is XML-incompatible, but it’s only about syntax, not semantics :)
P.S. Thanks a lot for the idea of using rem units to restore the ability to resize the font of inline-blocks after zero-fonr trick!
Another interesting option is to use the custom font in which the regular space characters have zero width (as suggested in the comments to the good Russian article on this topic).
@SelenIT: Yes, omitting closing tags is formally valid in HTML5, but is just unacceptable for me since I consider that part of HTML syntax as a big mistake in its design, so I’m not going to use this “feature” anyway. I prefer HTML document to be syntactically standalone, generally without need for any tag-name dictionaries to parse it. It’s ok if you are not a perfectionist like me though. ;-)
If you use HAML or another type of HTML preprocessor, you can just minify it on compile. And then your HTML is minified which is always good.
I was going to say the same thing! isn’t it a best practice to compress / minify HTML anyway?
I just put float them, put them in a div and set the divs position to relative, set its width and set margin to auto (so that they can be centred).
It’s advisable to use margin-right: -.25em; instead of 4px.
From where you know that the size of a single space is 0.25em?
Where can I find a reference about this?
@Taurif I’m almost certain that the spacing is dependent on the font being used and how that font is displayed by the browser. The negative margin method is not very reliable because of this uncertainty.
I’d recommend using the comment method, avoiding carriage returns between elements or just avoid designing elements that are dependent on zero white-space — it’s easier than you think.
Oh, so if I set the font size as
1em
then (for example) the size of a single space is0.25em
, so when I change the font size to2em
, then the size of a single space can be approximated as0.5em
.Of course, I would prefer using the comment or splitting the tag method. I just want to know more :)
@Taufix I don’t think that is totally correct. When a type of font triggers a space between elements that measures 0.25em, then it *should* remain 0.25em even when the font-size is increased. Em’s are a relative measure, they scale with the font-size.
The issue is it doesn’t really work like that. Different fonts can have different spacing specs, so for one font it may be 0.25em and for another it may be 0.2em. It’s even worse when you enlarge the font. Then, what was perfect can now be broken.
I made a demo for you to see here: jsFiddle Negative Margin Trick. You can also see how Firefox is different from Chrome here: Chrome v Firefox for space rendering.
Yep. Monospace have explained all!!!
Thank’s a lot!
I’d stay away form PX measurements, since the space is based on a single white space char. I use the following to tame the whole issue without much ado.
It’s pretty sweet and nearly bulletproof.
I just don’t get it. Why deal with all of the CSS shinanagens? You know what is 100% bullet-proof? Using the comment method or not using a carriage return between list-items. Anything else is a futile fight against browser inconsistencies and a slew of variables. Or, maybe I’m just crazy :P
The negative-margin solution is actually not accurate, the exact number depends on font-size and font-family. Some families do have an exact white space, like Courier New. I wrote about it a while ago although I wouldn’t recommend the solution I came up with back then, it’s way too complicated. Right now I use a negative margin (but I use em instead of px for obvious reasons) and I don’t bother too much about pixel perfection. Here’s my complicated solution: http://nerd.vasilis.nl/remove-whitespace-inline-block/
Its a problem I used to come across all the time when doing nav bars, was kicking myself when I realised what what the problem was…
Negative margin hack is probably taken from my CSS Box Framework https://github.com/vladocar/Box-CSS-Framework/blob/master/box.css at least I think that I was first to “invent” that hack.
The Negative Margin is not bulletproof solution, but is probably the easiest and most elegant hack when is comes to CSS Framework building.
Better results can be achieved with double font resizing but this solution is harder to implement and is code specific.
To me it seems that removing the closing
</li>
tags should not resolve this issue (that is, the spaces should not go away). Since HTML5 allows closing list item tags to be omitted, then the spacing should still be preserved. Omitting the closing tags should be exactly the same result as including them. I guess it’s assuming that the elements are butting up against each other, but that doesn’t seem right, especially if the new list item starts on the next line.I think that’s a bug in all browsers and should be reported. Maybe I’m wrong, but my reaction is that the spacing should be the same as when the closing tags are included.
The spacing IS preserved, but as a single space IN the element .
The element is closed on the occurrence of the next (or element.
So (especially when having large paddings), this is not (easily) visible.
Sorry for the fucked up post.
“The element is closed on the occurrence of the next <li> or </ul> element.”
wow, I just faced this problem today’s morning, I fixed it by giving the 102% width of the
but It was uncomfortable with the solution though!
I’m gonna try ur suggestions now
thanks!
This is very useful, thank you
The negative margin method doesn’t work quite right in Firefox. There’s a 1px gap between two of the li’s.
Font-size: 0 seems best to me. Second would be the weird html formatting, because even though it may look strange, it’s still perfectly correct and doesn’t add any extra markup or style hacks.
Very useful article, thanks!
Beautifully simple techniques to fix it! love the simplicity of the HTML 5 option,
Great article!
Float for me.
Btw, isn’t inline-block not advisable?
I’ve been using the inline-block method exclusively for many many years without a single issue. What most don’t realize is most of your time consumed with cross-browser debugging is *because* of floats.
With inline-block, there are two issues that can come up (this article address one), they are predictable and their solutions are easy. This should be a no brainer.
Floats were never designed to be used for laying out a page. Floats for this purpose are a hack. Inline-block is *the* way to layout a page.
A fine explanation. Thanks Justin.
I have been avoiding inline-block for a long time because of IEs and hate to use zoom fix.
Strangely, Facebook, Youtube, Twitter use float for this article and Twitter uses float to layout a page. Google using inline-block for almost everything.
You’re right. Nearly all developers use float rather than inline-block. This has bugged me to no end for a long time. I think it’s just habit, and no one has come along, kicked them in the arse and told them to break it.
I’ve been trying to get the word out for years. I even got so feed up with it, I wrote a jsFiddle trying to provide a link that I could just throw in a comment such as this: http://jsfiddle.net/Cerebrl/ZkQnD/
If using zoom is your main complaint, then don’t fret! Just throw it in an official IE conditional and your done (see my Fiddle)! This very, very simple work-around gets inline-block working all the way down to IE6 and is only presented to the very browsers that need it. To every other browser, it’s just a comment.
When I switched over to inline-block, my development time drastically decreased. My cross-browser testing is very easy, and everything is as it should be, the world is right.
The white-space issue is not as bad as one would think. Just try to avoid designs that require zero spacing; it’s easier than you think. If you do have a situation that requires it, just throw in the comment method or don’t place returns between elements.
Worst case scenario, just use floats, but I’ll tell you that I use floats so infrequently, that I’ve nearly forgotten how to clear them :)
A public service announcement! =D Nice! Because of that, I will try ditch float completely for my next project.
On other case, HTML5 with no closing tag? A dumb move by W3C and WHATWG.
“Made a mistake? Forgot to close a tag? Worry not! HTML5 will close them for you!”
Don’t they have more things to do rather than this?
Optional closing tags are not new invention. They were long-supported feature of HTML2-4, implemented in all existing browser engines. WHATWG and W3C just had to document this reality in the new standard, because of it’s design principles like ‘pave the cowpath’ and need for backwards compatibility with existing content and browsers.
In fact, optional tags are a big advantage of HTML because they just provide several correct ways to mark up the same robust and predictable DOM structure. For example, you can always be sure that any
TABLE
element will have at least oneTBODY
child, any other option is impossible by design. With “strict” XML parsing it’s not the case, in XHTML we can have thetable
withouttbody
as well as with it. So what is really “stricter”?Because of this “bug” I almost always use floats instead of inline-blocks (and a little bit because of IE7), but the former just feels “wrong”. Floats aren’t designed to be used for a navigation or things like that, inline-blocks is definitely the way to go. Regarding the gap, I definitely will have a look at the font-size trick in the future. Seems pretty decent.
I prefer to close up the spaces between tags. It’s not always pretty but it is the closest to the behaviour desired – no spaces. Negative margins always feel wrong in some way to me, margins get a lot get for positioning everything layouts, I never see them as a very elegant solution. I think word/letter spacing will become the best option.
I love the font size trick
Thanks a lot for this, it clears up a few confused moments I’ve had in the past. You should probably use em instead of px for the negative margin option.
This french post is pretty good on the topic :unwanted spaces.
Talkin’ about rem, letter-spacing, white-space, and the future : text-space-collapse.
I always use the font-size trick, which is short and efficient.
http://www.alsacreations.com/astuce/lire/1432-display-inline-block-espaces-indesirables.html
*forgot the link !
There is also the following CSS property:
white-space-collapse: discard;
However I don’t think any browsers actually implement it :(
I prefer the jQuery method as it is font independent. Saw it somewhere online recently. Don’t know if someone already mentioned this.
For example if there is some container that has inline-block elements inside:
$(‘#container’).contents().filter(function() { return this.nodeType === 3; }).remove();
To remove text nodes only if they contain just whitespace:
Bottom line: you have a bunch of hacks but no proper solution. The font fix is half-decent, the other fixes can only blow up in your face later further the line.
I don’t mind these type of articles, but it would be nice to warn people about the trouble they’re getting into when using certain “fixes”.
I always use inline-block, prety useful, i can determine the child align with the text-align property, center, left, right
this litle space is the only issue, i use the ident method to correct the problem.
PS: EXCUSE MY ENGLISH GRAMMAR
I try to always use inline-block, as it is in a sense, more semantic than float and also it doesn’t break any flow nor I need to add clearfix and such.
Since I usually develop in frameworks or at least not pure HTML, having my code to write the output inlined as it doesn’t output the spaces or line-breaks between tags and it also “compress” a little =D
And for those who says that my code becomes hard to read, I usually use any dev-tool available (usually in Chrome, but could be firebug in Firefox for example) which automagically converts and clean up the HTML. And my code that output the HTML is pretty well formated.
So for me is the best solution and I really don’t care that much for browsers that doesn’t support inline-block. =P
For the methods mentioned:
– Breaking the tags: I really hate this.. seems to me broken HTML… I don’t even use word wrap because of that
– Negative margin (or word-spacing): works ok if you take care of your font and font-size
– Float: prefer not to use if possible (I even try to change the CSS framework to inline-block when possible)
– Comments: it works well for pure HTML, any other way to generate HTML becomes hard to write/maintain
Great post Chris
I rarely make anything that relies on no spacing, but when I do I just don’t put spaces between list tags.
It’s the most reliable method imo.
Instead of breaking up the tag on multiple lines, i prefer this syntax:
Or this:
The first one is exactly what I do! It works well and is easy to read.
This is what I’ve been doing:
… but I think I like your first one better! It looks much cleaner, and it’s much easier to read.
By the way, Justin, I completely agree with all of your comments! I made the switch a few months ago, and now I barely ever use floats. It’s SO much easier. Plus, by using the HTML syntax above, I don’t have to mess with browser inconsistencies and crazy hacks. It just works! It’s even easier when used with LESS. I just do this:
To echo an above poster,
If its a nav, just float the dang things… Sheesh, why make more work when it’s not needed?
I call this the “this seems too easy, it feels like I’m cheating…” phenomenon among the web creative.
Like can you imagine if you could just set border-box on everything and not have to resort to pixel perfect military precision like calculations for paddings and margins…
Nah that would be too easy, just wouldn’t be able to sleep right…
Lol, I’m just sayin’. But some great alternative solutions. I hadn’t come across the negative margin before.
what about not closing the LI tags?
if you are using html ( NOT XHTML – important ), then the LI elements ( google for more of those ) will be closed automatically and will have no spacing ( no empty text node )
check http://jsfiddle.net/stryju/6S5N8/ for explaination
Hmmm.. I use the float technic.. its so simple..
Trust me, inline-block is simpler. I’m going to assume you pretty much exclusively use float and rarely (or never) use inline-block, and because of this, float seems simple because it’s familiar to you, it’s comfortable.
Inline-block is superior to float and is much simpler in almost every layout configurations. Floats need clearfixes (how many do we need again for the different browsers?) all the time, and they cause the majority of cross-browser inconsistencies. That doesn’t sound “so easy”.
If you design right, the majority of the time you shouldn’t have to worry about the white-space at all, and when you do, it’s a very easy fix. The example white-space issue Chris used above is really easy to fix without even having to worry about white-space — just put the red background on the ul and you’re done.
Like I said, just think about the design, and you can use inline-block without worry. Once you “convert” over, your development time will noticebly decrease.
@Justin, we don’t need to clear float if we set the parent element to have overflow hidden, so no need for clearfixes. I think there is a design where pixel perfect is important and that is where I find float to be better. It is might be easier for me as well as I have used float for many years, so I know more or less the behavior of it in most browsers.
That said, inline-block is a very easy solution for design that doesn’t need pixel perfect and I only use it for that case. I’m not usually design sites (there are designers, I’m front-end dev), so I only choose whatever works best for their design. :)
@Jeffri I still don’t understand the argument though. Pixel perfection (I’m assuming your mean zero spacing) CAN be achieved with inline-block. I do it all the time. Just get rid of the space between the elements (either literally doing it or using a comment) and you’re done. That’s it.
Plus, the overflow: hidden method for floats seems like a hack because it certainly isn’t logical behavior for CSS. The danger with this is browsers could easily see it as a bug and fix it, and there went your layout. It also can’t be a bullet-proof method for all/old browsers.
I use
font-size: 0px;
LESS makes this the most effective method IMHO since with LESS, you don’t need to worry about the relative font sizing issue which may occur otherwise.
We use diferent stuff until we start “Html minification” and this remove all spaces downsizing html files so we dont worry for these extra spaces anymore.
use
* {
margin: 0;
padding: 0;
}
Leaving off the closing tag looks like the most elegant solution to me (though I wasn’t even aware it was allowed!). Funky formatting and extraneous CSS feels hackish.
Thx Justin. I have been a float guy and guess i really need to switch. I believe pad/phone sites done sized w/ media queries are sucessfully done via inline-block.
You’re welcome. I’m glad I could help! Yes, considering the amount of variables now in web design, no longer is it just Webkit, Mozilla and IE for desktop, but a slew of mobile browsers as well, we need bullet-proof ways to ensure our designs don’t break.
Since floats are inherently buggy since they’re taken out of document flow, different browsers have to decide how to render them and their interaction with other elements. It just makes more since to use something that follows a traditional since of document flow, so there is much less interpretation. I hope it helps you with your future development.
good job justin :) i love this part ‘Skip the closing tag’
I’m using the following code.
ul {
word-spacing: -1em;
display: table;
display: block\9; /* hover bug for IE8, 9 */
width: 600px;
}
li {
word-spacing: normal;
display: inline-block;
vertical-align: top;
/display: inline;
/zoom: 1;
width: 100px;
}
The easiest solution is to just put it all inline:
Why are people afraid of the “Remove the spaces” technique? Shouldn’t we be compressing HTML to remove unneeded white space anyway?
I couldn’t read all the responses (too many!) but the negative margin fix doesnt work on Chrome either!! (Chrome 18.0.1025, Mac OS X 10.7.3)
I knew the negative space and floating thing. but, i learned the font-size zero thing.
By using -ve space it will break in IE as you said before. with floats we might need to clear the float with some addition unnessecary html something like
<div class="clear"></div>
.But, by using font size 0. is just one thing we need to do
Thanks Chris
It worth it…
Well, I just change the html markup.
if is display: inline-block, then there would be a space, however, I have no space in the code so there is none on the screen.
I use inline-block a lot lately, so I use this code structure everywhere, help more than css hacks or whatever
If you don’t want spaces between words than simply remove them in the HTML. The spaces between inline-blocks are no different. Negative margins is just a hack thats bound to cause difficulties later on.
Removing the spaces in the HTML is a sinch if your view only echos HTML and no leading or trailing whitespace. This is how I do it.
Great topic. Inline block elements are a bit tricky and it’s nice to see different approaches to remove the spaces.
But, inline-blocks are not tricky, at all. That’s what I find so strange about this whole debate. They couldn’t be more simple. If you don’t want the white space, remove it in the markup. It’s that simple.
http://jsfiddle.net/mJjCc/
Relevant Code:
While 0=0rem, using the suffix in this case protects browsers without rem support. While negative word-spacing won’t fix all browsers, it also appears to do no damage. By combing these rules, we should be able to eliminate unwanted spacing in many of the modern browsers and maybe a few older ones as well.
As you can see from my previous comment, I recently set about tackling this exact same issue. I had a moment today to do some cross-browser testing of my code. My parameters for coding an inline-block collapsing whitespace fix were:
– No pixel resetting of fonts.
– No negative margin calculations for differents fonts and/or browsers.
– Apply inline-block but remove whitespace between them universally, unobtrusively and across browsers and platforms.
I believe I was successful in meeting those requirements in this jsFiddle:
http://jsfiddle.net/jTSnd/
The following browsers were tested and performed as expected:
– IE 6, 7, 8
– Opera 11.01 Windows
– Opera 11.64 Ubuntu
– Chrome 19 Windows
– Chrome 19 Ubuntu
– Safari 5.1.7 Windows
– Firefox 12 Ubuntu
– Firefox 10 Windows
Here is the relevant CSS:
I always use the negative margin method, but the floating method, simple as it is too.Thanks your share.
If you want one element on the left and one on the right then a float is better – unless you know the width between then to add margins.
Inline is great BUT sometimes you need inline-block and ie6&7 can struggle with this, even when using zoom which might not be appropriate at that moment.
Using any kind of negative margins is always going to cause trouble down the road if font size changes and you need pixel perfect. Also the added spacing is above and below in my experience.
The font size thing look a good solution but I wonder about what google does if it sees font-size:0?
Would love to be able to float but still have things centrally aligned. Unless I have misunderstood doesn’t the example http://jsfiddle.net/kpadx/ just use padding to achieve the effect which is reliant on knowing the width?
When using inline-block, aligning the elements left, right or center is extremely easy. Just use text-align! The inline-blocks act the same as text-characters, so text-align works flawlessly in manipulating their position.
I’ve even shown how to do it with one left and one right. See here: jsFiddle
IE6 and IE7 work perfectly fine with inline-block, but you have to use both display: inline; WITH zoom: 1; The easiest least hackish way to do this is use a conditional comment for IE7 and under and copy all your inline-elements into a style tag and give them the necessary properties.
I have an example for this here, just look at the HTML: jsFiddle
I hope this helps. Inline-block is a very beautiful thing, but because we’ve been addicted to floats for so long, many are just not familiar enough with the property to appreciate it.
I’d be quite annoyed if I had to go in after your code, Justin, to fix or make alterations to your elements. I don’t want to have to hunt for where the next beginning / ending tag is over and over — not to mention having to deal with code generated dynamically where adjusting the white space may be more of a nightmare than anything else.
Those spamming “just use float!” apparently have never tried centering the text.
After reading all the comments, I think it’s safe to say there’s no clean way of implementing this without a variety of inconsistent hacks.
@Nick
Lol, I’ve been using inline-block for years within teams of other developers and have never once had any complaints about my code style (they usually love it).
Here’s the big reveal: I rarely ever have to deal with the whitespace issue discussed here, and that’s because it’s easy to design interfaces that don’t require zero whitespace between elements. This whole thing is really a false issue.
If you design knowing inline-block will be used, you can easily alter how you design seamless interfaces with no issues of having to deal with unwanted whitespace. I do it day-in day-out in the most complex web applications.
When I do have the issue, I just use the comment method. And, it’s almost always within large sections concerning layouts that are never dynamically manipulated, so it’s never really an issue. Once I’m designing the internal elements of a web page or app, I almost always want padding between the elements.
Anyway, thanks for the comment, but I don’t think your argument holds water. Take care.
@Justin,
There are more bad developers than good out there so having no one make a point of it doesn’t exactly ‘hold water’. I have looked at the code provided and I’m already annoyed by it let alone in a larger web application environment.
You speak of designing knowing inline-block will be used: I surely hope you don’t mean you’re basing your designs on the use of inline-block rather than what the UX / branding / design calls for.
I’d love to see some examples of your websites where you’ve designed “knowing inline-block will be used”.
There are too many wish-washy developers out there with sub par development techniques, so you’ll have to excuse me for questioning the validity of a hack given those on the forefront of these specs don’t bother wasting their time with it.
@Nick
“There are more bad developers than good … ”
I’m aware, and I don’t work with them.
“I surely hope you don’t mean you’re basing your designs on the use of inline-block rather than what the UX / branding / design calls for.”
I’m not implying that at all. I’ll give an example. Many designers, when building a horizontal navigation bar, will place backgrounds on the li’s and so they need zero whitespace to prevent gaps. Why not just place the background on the ul’s instead? Now, your nav doesn’t require zero whitespace. If an li needs a hover state, just give that li a different background, leaving the others with none.
I also see so many designers just do things because floats allow them to do it, not because it’s the right way or the best way, but just because they can. It’s more about just changing how you solve design problems. I’m *not* talking about altering the aesthetic or brand of the interface to allow inline-block, I’m talking about changing how you solve problems that designs present.
“I’d love to see some examples of your websites where you’ve designed “knowing inline-block will be used”.”
Well, most of what I do is under NDA and behind firewalls, but you’re more than welcome to visit Ka-Prow Bistro to see one of my few public clients.
You are also welcome to visit my Dribbble account where you can see snapshots of some of my work; visit my Forrst account to visit some of my design and development contributions; check me out on Quora where I talk about application development, UX, neuroscience and psychology.
I hope that helps.
I am using :
Sometimes the font size in browsers that do not comply. For example, in IE 7-9
My friends, what alternatives are there?
This should do the trick:
I use inline-block with close and open tags butting up to one another. You can still format your HTML code nicely and it uses no hacks. All I do is include all inline-block rules as inline in an ie6-7 file in an if statement.
I loathe floats for layout. Even the name “float” suggests a lack of real place and control of the elements in question.
“Where would you like these 2 sofas mate?”
“Oh if you could ‘float’ them next to each other that would be great. Don’t worry. I’ll put something meaningless and invisible underneath them so the floor knows they exist.”
“Eh? WTF?!”
Yes, another voice of reason! Thank you!
There is an easy not well known way to avoid spaces between inline-blocks, and is this:
Yea I know it’s terrible, but it’s the fastest solution out there.
I know it because I had the opposite problem, I had an html compressor on server side which was minifying my html code. The issue was that I needed space because otherwise
text-align: justify
won’t work (read it on specs)!So yes, removing spaces between the tags solve the issues immediatly.
font-size solution without lose parent font-size
Negative margine keep some problem about browser crossing.
Thanks for the “comment solution” and “zero font size”, you saved me.
I just want to make a shameless plug for my white-space project. With it, you can write
white-space: none;
in your external CSS. There is lots of information in the README, so I won’t go into details here.TLDR; It fixes your white-space issues.
Thanks for the tips. I floated my spans
Thanks for the good article.
This formatting looks good enough (especially if you have links instead of plain text) and is doing the job.
There’s actually a really easy way to remove whitespace that’s both easy and semantic. It’s called a custom font with zero-width spaces. Then you just change the font on the container and voila. Here’s a download to the font I just cooked up in font-forge with the css @font-face declaration included. Suit to taste. zipped zero-width space font (click File > Download to save to your computer)
This is probably the simplest way I have seen to combat white-space. I’ll try it out in my current project.
Well, that was a good answer to a 2h long wait trying to find where does the white space come from and refusing to use floats.
Thank you!
Oh god! Thank you for this topic!!
I will never thought that the point was because (\n) or (spaces) between html tags.
I’m using from now on the () solution =)
Man, CSS is a depressing medium to work in. Poor implementations and gotchas everywhere.
Hello all,
Could someone e-mail the link on how to avoid whitespaces between news blocks in Dreamweaver? I know I’m doing it wrong with absolute AP Divs by moving them downwards every time a new story comes in. Basically, I’m selecting all AP divs and moving every single element which is an overkill when there are over 10 stories on a page.
I use a background image encapsulated into AP divs. Is there a way (CSS or any other) of sliding all previous stories down? Would appreciate the solution, not the discussion of how outdated AP divs are. I haven’t arrived to a perfect CSS solution yet.
Here’s the link – http://liep2vsk.edu.lv/Aktualitates.php
I suggest you to start by dropping entirely Dreamweaver (it’s not useful anymore, just a waste of PC resources). Absolutely positioned divs are not bad, no issues with them even if they are old.
However, your code is unreadable for a human, considering is built with dreamweaver it’s all cluttered with “non-human” names, I can’t help you at all on that.
I would have never imagined that a line break in the code would count as white space when rendering. Since I can’t use floats for the specific markup I have, I went with DRaev’s solution, because it looks clean and it’s very readable.
Thanks for the tips. I floated my spans
I think we should cooperate to get the best possible solution without changing code style.
Afaik, there seems to be at least two ways:
One is to use a custom font with spaces character of zero width; should be working fine and I think we can easily add a custom whitespace, in the case we are already using a font via @font-face. That way the font defines some part of the UI…
Two is a white-space: none; polyfill. Never tried but a polyfill is a common solution to tricky issues.
It would be cool to have some serious, extensive testing on them.
This great man! Removing the space the spaces is a brilliant and yet so stupidly simple (at least for me).
I owe you a beer at least!
Thank you, friend! You saved my day :)
this’s simple :
I’ve created a compressor for Jekyll. It’s a layout with lots of Liquid inside, that removes all the unnessecary whitespaces during the rendering. It works without external plugins, so you can use it on Github Pages.
You are awesome! Thanks.
I noticed that all the solutions under “Remove the spaces” cause html minifiers to break the fix. So something to consider if you are looking for a production ready solution.
If you are using a html minifier, you don’t have any white space issues. It’s only an issue if you have source code line breaks.