
CSS Layouts: Understanding the Differences Between Grid, Flex, and Float
To achieve a variety of web layouts, you might set the CSS display:
property of a parent element to flex
or grid
or use the float property. Choose wisely. Each layout technique has its pros and cons as well as ideal use case scenarios.
Grid
With grid, it’s easy to set up an entire layout design system for your website. On a macro scale, you’ll have your styling up and running in no time. Layouts may be nested within other layouts and grid also allows you to create extremely complex arrangements with precision. Grid isn’t best for quick centering or placing an image within a larger text article. These types of layouts are best handled through other methods.
Flex
Flex includes many sub properties that can be especially useful. For example, flex-grow
and flex-shrink
allow columns to change width and proportion depending on the user’s view. justify-content
allows for evenly spaced items or perfect centering. This is a great tool to let smaller UI elements look their best on any device. Unfortunately if you want to layout larger elements on the page, you would probably want to add margins and then do a little math to make sure it looks the way you want it to look. That can take time. In addition, each section of your design must be a row with a separate flex tag on it. This rules out using flex for more complexly designed grid systems. However, it is actually because of the separate tagging that flex is seen in many frameworks and design systems.
Float & Clear
Float & Clear is familiar. This is a great way to set an image within a larger text article.
However, it’s not a very practical way to set up an entire web page layout. If you’re not careful, it can get buggy pretty quickly, and it’s a little bit of a mess trying to clean it up. This layout method just doesn’t have as many built-in properties as Grid or Flex and cannot create complex layouts.
What’s Best?
My definition of best would be the layout method that requires the least amount of lines in css to achieve the most complex layout. Grid definitely wins. Its syntax is efficient and makes sense. However, I think there’s a place for all the layout methods, and they can and should be combined where necessary. When creating a custom HTML/CSS website, I recommend using grid to layout your site, float to add that image to your blog post, and flex to get that tiny pop-up UI element looking fantastic!
Citation: This article was originally written for DGMDE20 at Harvard Extension School. Check out the awesome classes you can take: https://www.extension.harvard.edu/