Elfayer
Elfayer

Reputation: 4561

How to place divs one next to another without floatant?

I managed to place two divs one next to the other using float: left, but the div below doesn't display properly : http://jsfiddle.net/N4kE3/2/

And with this css for each div :

display: inline-block;
width: 50%;

see: http://jsfiddle.net/N4kE3/3/

They are one above the other. I have to put width: 49% to make them be one next to the other.

How is that possible ?

Upvotes: 0

Views: 64

Answers (2)

Turnip
Turnip

Reputation: 36632

If you wish to keep your floats you could use a clearfix on the container:

Working demo

#action:after {
    content: "";
    display: table;
    clear: both;
}

If you wish to useinline-block you need to remove the white space in your markup:

Working demo

This..

    <div id="action">
        <div id="buy" class="action">Buy</div>
        <div id="sell" class="action">Sell</div>
    </div>

Becomes...

<div id="action">
    <div id="buy" class="action">Buy</div><div id="sell" class="action">Sell</div>
</div>

.. otherwise the white space will be taken into account when calculating the widths making 50% + 50% + whitespace = more than 100%. Thats just how inline-block works.

Upvotes: 1

Arnold Daniels
Arnold Daniels

Reputation: 16553

The space between elements is displayed. Imagine <strong>Hello</strong> <em>world</em>. This is displayed as "Hello world". See the space between Hello and World.

An enter and multiple spaces are collapsed to a single space.

  <strong>Hello</strong>
  <em>world</em>

becomes "Hello world".

The same is happening with your divs. They are both 50% of the screen, but the space also takes up 10 pixels, pushing the 2nd div to the next line.

There are several ways of solving this. Using float, using display: table-cell or (as I usually prefer) by eliminating the space between the divs using XML comments <!-- -->.

<div id="content">
    <div id="action">
        <div id="buy" class="action">Buy</div><!--
     --><div id="sell" class="action">Sell</div>
    </div>
    <div id="other">test</div>
</div>

See the fiddle

Upvotes: 1

Related Questions