Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 228
Michel Avatar asked Nov 23 '12 08:11

Michel


People also ask

How to place two divs next to each other in HTML?

By default, if you create two div elements in HTML code, they are placed one below the other. If you want to place them next to each other you would require to use a CSS property float. As the name goes the float property specifies how an element should float in the webpage on the left or the right!.

How to align two divs horizontally in HTML?

To align two divs horizontally in HTML, use the float CSS property with left value. You can try to run the following code to learn how to align divs horizontally:

How to display two equal size <div> elements next to each other?

In this solution we use display: flex style property for our wrapping <div> element, so in both children divs we can set flex: property value with 1 to display two equal size <div> elements next to each other. 2. Using float and overflow properties

How do I place two elements next to each other?

If you want to place them next to each other you would require to use a CSS property float. As the name goes the float property specifies how an element should float in the webpage on the left or the right!. none - This is the default behavior.


1 Answers

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.

like image 106
Ben Avatar answered Oct 29 '22 05:10

Ben