On two different projects I learned two different methods of positioning two div
s 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>
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!.
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:
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With