Michel
Michel

Reputation: 23615

How do I position two divs horizontally next to each other?

On two different projects I learned two different methods of positioning two divs horizontally next to each other. Is one better than the other, or is it just a matter of personal taste, or maybe one is only working by coincidence?

Method one:

.container,
.div1,
.div2 {
  border: 1px solid red;
}

.div1,
.div2 {
  float: left;
}
<div class="container">
  <div class="div1">
    DIV1
  </div>
  <div class="div2">
    DIV2
  </div>
  <div style="clear: both;"></div>
</div>

Method two:

.container,
.div1,
.div2 {
  border: 1px solid green;
}

.div1,
.div2 {
  display: inline-block;
}
<div class="container">
  <div class="div1">
    DIV1
  </div>
  <div class="div2">
    DIV2
  </div>
</div>

Upvotes: 21

Views: 36235

Answers (4)

Ben
Ben

Reputation: 57237

The first one is more widely supported in older browsers, but float usually leads to some weird behavior (not bad, nothing that will break your design, just a little unexpected).

You'll crank away with inline-block only to find something broken in your design when you check some random browser later on in the lifecycle.

I usually stick with float, and only float.

EDIT

Revisiting this answer almost 10 years later and my recommendation now would be stick with flexbox and only flexbox. Try out https://flexboxfroggy.com/ if you need some practice.

Upvotes: 14

Alex Gyoshev
Alex Gyoshev

Reputation: 11977

Both are valid CSS that does not work by accident -- it depends what you need.

When using floats, you will need to clear them (as in the posted code); when using inline-blocks, this is not necessary. Also, you can use text-align to align the inline-block elements, while there is no float: middle. You can also use the vertical-align property to align the boxes as you need.

As others said, there are some issues with inline-block, most notably that older IEs don't support it (much) on block elements (note that it works fine on inline elements, like <span>). You can work around that with the following hack:

.selector {
    display: inline-block;
    *display: inline;
    zoom: 1;
}

Upvotes: 4

Selvamani
Selvamani

Reputation: 7684

Use Float(First method). Because its support all browser and its easy to handle. Here the link you can learn more

Upvotes: 2

Jan Hančič
Jan Hančič

Reputation: 53931

If you are using the second method then there's no point in using a DIV if you are then turning it into a inline element. Just use a SPAN tag.

So if you are trying to align block level elements/tags, use the first method.

Upvotes: 1

Related Questions