How can I horizontally align my divs?
Solution 1:
To achieve what you are trying to do:
Consider using display: inline-block
instead of float
.
Solution 2:
Try this:
.row {
width: 100%;
text-align: center; // center the content of the container
}
.block {
width: 100px;
display: inline-block; // display inline with ability to provide width/height
}
DEMO
having
margin: 0 auto;
along withwidth: 100%
is useless because you element will take the full space.float: left
will float the elements to the left, until there is no space left, thus they will go on a new line. Usedisplay: inline-block
to be able to display elements inline, but with the ability to provide size (as opposed todisplay: inline
where width/height are ignored)
Solution 3:
Alignments in CSS had been a nightmare. Luckily, a new standard is introduced by W3C in 2009: Flexible Box. There is a good tutorial about it here. Personally I find it much more logical and easier to understand than other methods.
.row {
width: 100%;
display: flex;
flex-direction: row;
justify-content: center;
}
.block {
width: 100px;
}
<div class="row">
<div class="block">Lorem</div>
<div class="block">Ipsum</div>
<div class="block">Dolor</div>
</div>
Solution 4:
Using FlexBox:
<div class="row">
<div class="block">Lorem</div>
<div class="block">Ipsum</div>
<div class="block">Dolor</div>
</div>
.row {
width: 100%;
margin: 0 auto;
display: flex;
justify-content: center; /* for centering 3 blocks in the center */
/* justify-content: space-between; for space in between */
}
.block {
width: 100px;
}
The latest trend is to use Flex or CSS Grid instead of using Float. However, still some 1% browsers don't support Flex. But who really cares about old IE users anyway ;)
Fiddle: Check Here