Stop Using Float in CSS - Here Are Your Alternatives

Throughout my years of working in CSS, the property that causes the biggest mess in the layout is float. Whenever float is used, unexpected behavior occurs at some point in your layout and design. I’ve also seen a few beginners who stumbled upon issues like this. They use float then when problems arise, they find it hard to link it back to the floated element.

For this reason, I’m giving you a few options you can use to achieve the same effect you need with float while avoiding the mess. These options target block elements, as for inline elements I assume you know you can use text-align with.


You’ve probably used margin: 0 auto; a lot to center a block element horizontally. You can also use margin to align a block element to the left or to the right. If you need to align it to the left, then set margin-right: auto and margin-left: 0;. If you need to align it to the right, then set margin-left: auto and margin-right: 0;. Basically, to align a block element to one side horizontally, set the margin of that side to 0 and the opposite side to auto.

Align with Flex

Using flex, you can align your elements even more flexibly. In particular, to align your element horizontally to the left or to the right, first, you need to add display: flex; to the parent. Then, you have two options depending on the flex-direction you will use. If you use flex-direction: row; then set justify-content: flex-end; to align the item to the end of the parent element or justify-content: flex-start; to align the item to the beginning of the parent element. This also allows you to apply a similar style for both right-to-left and left-to-right layout, as flex-end in left-to-right will align the element to the right and flex-start will align the element to the left, whereas in right-to-left it will be the opposite.

Align with Grid

Now, this one may be more complex depending on your use case, but you can also align blocks using grids. What you need to do is set the display of the parent element to grid, then, in the case of one block in the grid that you just want to align to the right, you can set grid-auto-columns: calc(100% - BLOCK_WIDTH); if you have the block width set. If not then this won’t be necessary. Then, set grid-area: right; on the block you want to align and it will be aligned to the right.

#css #beginners

Stop Using Float in CSS - Here Are Your Alternatives