2

could you please explain to me why these 4 divs are not staying next to each other? There are 4 divs, I set their width to 25% so they fill the whole page and yet 1 div is pushed under the others. I have to set the width to 24% to have them stand next to each other. How come? In my book 4x25% = 100%.

http://jsfiddle.net/cm2K6/

.four {
    display: inline-block;
    vertical-align: top;
    width: 25%;
}
Kimberley Furson
  • 497
  • 1
  • 7
  • 17

4 Answers4

5

A "Enter" in HTML code is equal to a space, if you remove those spaces </div><div>, you'll lose the spaces between inline-blocks (or inline elements in general).

Example: http://jsfiddle.net/cm2K6/3/

No need to go for float:left;, box-sizing, word-spacing or anything similair unless you want your code to look good.

Marcel
  • 1,279
  • 10
  • 12
2

it's because display: inline-block has a natural spacing between elements. You can use float: left instead:

JSFIDDLE

jmore009
  • 12,863
  • 1
  • 19
  • 34
  • What do you mean by "natural spacing"? Is it browser defaults? http://jsfiddle.net/cm2K6/8/ – Morpheus Mar 02 '14 at 21:54
  • yes, you can read more about this and some solutions here: (http://stackoverflow.com/questions/1833734/display-inline-block-extra-margin) – jmore009 Mar 02 '14 at 21:56
  • @Morpheus Yes, that's the normal behavior of inline elements in inline flow. Just like when you put an image next to another one; or put a button beside a text input. – Hashem Qolami Mar 02 '14 at 21:57
  • 1
    @Morpheus ditch the spaces in your html code to ditch the spaces in the output, see fiddle in my post – Marcel Mar 02 '14 at 21:57
  • also a solution, however for people that use something like haml that would not be an option, but it's one to consider – jmore009 Mar 02 '14 at 22:01
2

Inline and inline-block elements let a single significant whitespace character affect their layout Remove any whitespace between the </div> and <div> tags

http://jsfiddle.net/cm2K6/7/

berkeleybross
  • 1,314
  • 2
  • 13
  • 27
0

The trick is to not let spaces in your HTML between divs. It's strange I know, but it works. You can use a margin-right: -1% if you still want to keep your inline-block, otherwise go for floating elements.

radubogdan
  • 2,744
  • 1
  • 19
  • 27
  • For this particular problem it does. I suggest you to read [this](http://designshack.net/articles/css/whats-the-deal-with-display-inline-block/) go search for "The Whitespace Issue". Thanks – radubogdan Mar 02 '14 at 22:04
  • What @MrLister means is the spacing is not caused by the `display` attribute. – digitalextremist Mar 02 '14 at 22:28
  • Also, the space is not 1%. – Mr Lister Mar 02 '14 at 22:29
  • Ah Ok, sorry for this. I know that display attribute is not causing the space, that's not what I wanted to suggest. I will edit this. The space is not 1% but it's convenient. – radubogdan Mar 02 '14 at 22:34