1

I wanted to position two divs side by side based on the size of the container div. The second div positioned below the first because there is a 4 pixel gap between them somehow. Why and more importantly what is that? Margins, padding and border is 0px to make it cleaner.

<div id='container' width='300'>
  <div id='left' width='150'></div>
  <div id='right' width='150'></div>
</div>

I know you can use float to achieve the goal but I want to know the cause.

JSFiddle here.

Also I have noticed when I get the width() of an element I didn't get the same number what's in the debug window. Any clue?

Thanks!

Edit: OK, I see know it's a ' ' between them because of the new line character. It doesn't seems to matter if it's 'inline-block' or 'block' though. However setting the container to display as 'flex' appears to be a solution.

(Also thank you for the suggestions on how to remove the space even if there are white space characters between the divs! I still can't upvote sadly because of low reputation...)

RawBits
  • 53
  • 8

3 Answers3

2

Compare:

<div>
  a
  b
</div>

with:

<div>
  ab
</div>

Elements that are display: inline-block are treated like text.

There is space between them because they are inline elements with white space characters between them in the markup.

Put the start tag for the second div immediately after the end tag for the first one, without any spaces, tabs or new lines between them.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

The problem is that inline/inline-block elements respect white spaces, including new line characters, they also take space. Hence, if you remove all white spaces between elements it will fix the issue:

<div id='container'>
    <div id='left'>&nbsp;</div><div id='right'>&nbsp;</div>
</div>

Demo: http://jsfiddle.net/za2uu8ze/2/

Of course manually (or programmatically) remove all spaces between tags is not very elegant solution. Unfortunately there is no clean CSS property to ignore them. However you can set font-size: 0 on wrapping container level and reset it back to necessary font value on elements level. This will effectively make white spaces 0-size:

#container {
    /* ... */
    font-size: 0;
}
#container > * {
    font-size: 16px;
}

Demo: http://jsfiddle.net/za2uu8ze/3/

dfsq
  • 191,768
  • 25
  • 236
  • 258
0

Its because of inline-block element:-

You can try like this:-

<div id='container'>
    <div id='left'>&nbsp;</div><div id='right'>&nbsp;</div>
</div>

OR

<div id='container'>
    <div id='left'>&nbsp;</div><!--
 --><div id='right'>&nbsp;</div>
</div>
Mukul Kant
  • 7,074
  • 5
  • 38
  • 53