CSS Floats: Tips for Newbie Coders
Floats have a bit of a bad rep, and with new tools like Flexbox or CSS Grids, it’s not hard to see why. Floats can be bit tricky, and maybe not as fun to work with, but the reality of the situation is this: it’s not up to you to decide if you are going to be using floats or not. I can imagine what you might be thinking after reading that. “But it’s my code. I’m building this site so it’s up to me to decide which tools I want to use.” Unfortunately, unless you are freelancing (and maybe not even then), this certainly is not the case.
Just imagine, you’re a Junior Developer and you’ve finally found the company of your dreams. There’s just one thing, a significant amount of their audience is still using browsers that are not 100% compatible with Flexbox. You decided long ago that floats were obsolete and haven’t used them for months, if not longer. There is another applicant who has a similar amount of experience as you, but they’ve kept up with floats and can use them as well as they can flexbox. Who do you think is going to get hired? Don’t put yourself in a situation where you might miss out on a great opportunity because you’ve decided everyone should just get on board with flexbox already.
You don’t need to be a Master Floater to have success at using them, but you do need to have a general understanding of float principles, and maybe know to use a couple tricks here and there to ensure that your layout is accomplished with little issue. Here are a three tips that have helped me to have success with floats.
Tip 1: Always (mostly) float left.
Seriously. Strange things can happen when you use float right and if you are not that Master Floater we talked about, you could run into problems that you do not realise are coming from your right float. Did you know that if you float a container right it will reverse the order of the list items within? Bummer.
Tip 2: Add a background colour to the parent. You’ll thank me later.
Heck, add background colour to the parent and all children. This will help you to see more easily where potential issues in your code are. Once you’ve nailed that float down, the backgrounds colours are easily removed and you may have just saved yourself a huge headache.
Tip 3: Always clearfix the parent.
Often times when I’m having issues with my floats it’s because I’ve forgotten to add clearfix to the parent container. If for some reason I haven’t added background colours to my divs, and I can’t immediately recognize that the parent container has collapsed, then it can take me a while to go back through my code and see where I’ve gone wrong.
This is just a few of the things that I have found are important for me to remember when I’m trying to master my floating techniques. What kind of tricks do you use that have given you success with floats?