In recent years, CSS layout has come of age, with dedicated tools for complex layouts replacing the various workarounds of using tables, floating, absolute positioning and so on. Flexbox (or the Flexible Box Layout Module) was the first of these dedicated layout modules, followed by CSS Grid Layout. In this article, we provide a user-friendly introduction to flexbox.
With the introduction of CSS Grid Layouts, you may be asking if flexbox is needed at all. While there is some overlap in what they can do, they each have very specific purposes and roles within CSS layout. As a very general rule, the sweet spot for flexbox is layout in one dimension (say, a string of similar items), while Grid is ideal for layout in two dimensions (such as the elements of a whole page).
That said, flexbox can be used for full-page layouts, and thus provides a handy fallback for Grid layouts in browsers that don't yet support Grid. (Admittedly, support for Grid has rapidly spread across most modern browsers, but support for flexbox is still wider, which is handy if you need your layouts to work in some of the slightly older browsers.)
Advantages of Using Flexbox
Some of the advantages of flexbox are:
- page content can be laid out in any direction (to the left, to the right, downwards or even upwards)
- bits of content can have their visual order reversed or rearranged
- items can “flex” their sizes to respond to the available space and can be aligned with respect to their container or each other
- achieving equal-column layouts (irrespective of the amount of content inside each column) is a breeze.
To illustrate the various properties and possibilities, let’s assume the following simple layout for some of the demos in this article:
[code language="html"]
<div class="example">
<header>
header content here
</header>
<main class="main">
<nav>
nav content here
</nav>
<div class="content">
main content here
</div>
<aside>
aside content here
</aside>
</main>
<footer>
footer content here
</footer>
</div>
[/code]
The first step is to place the elements within .main
, i.e., <nav>
and <aside>
, side by side. Without flexbox, we’d probably float all the three elements, but making it work as desired wouldn't be very straightforward. Moreover, the traditional way of doing things would present a well-known problem: every column is just as high as its content. As a consequence, you would need to set an equal height for all three columns to have the same length, or use some sort of hack.
Enter flexbox to the rescue.
The post A Friendly Introduction to Flexbox for Beginners appeared first on SitePoint.
by Christian Krammer via SitePoint
No comments:
Post a Comment