Content:
Flexbox is a new way to arrange blocks on a page. This is a technology created specifically for the layout of elements, as opposed to floats. Via Flexbox You can easily align elements horizontally and vertically, change the direction and display order of elements, stretch blocks to the full height of the parent, or nail them to the bottom edge.
UPD from 02.02.2017: made a handy flexbox cheat sheet, with live demos and descriptions from the spec: Flexbox cheatsheet.
The examples use only the new syntax. At the time of this writing, they are most correctly displayed in Chrome... In Firefox they work partially, in Safari they do not work at all.
According to caniuse.com, Flexbox not supported by IE 8 and 9 and Opera Mini, and not all properties and / or prefixes are required in other browsers.
This means that the technology cannot be widely used right now, but it is high time to get to know it better.
First, you need to know that flex items are positioned along the axes. By default, items are arranged horizontally - along main axis - the main axis.
It should also be borne in mind that when using Flexbox float, clear and vertical-align do not work for inner blocks, as well as properties that set columns in the text.
Let's prepare a testing ground:
One parent block (yellow) and 5 children.
Display: flex
And now add display: flex to the parent element; ... The inner divs are lined up (along the main axis) in columns of the same height, regardless of the content.
display: flex; makes all children flexible - flex, not inline or blocky as they were originally.
If the parent block contains images or text without wrappers, they become anonymous flex items.
Display property for Flexbox can take two values:
flex - behaves like a block element. When calculating the width of the blocks, the layout has priority (if the width of the blocks is not enough, the content can get out of the border).
inline-flex - behaves like inline-block. Content priority (content expands blocks to the required width so that lines fit as much as possible).
Flex-direction
The layout direction of the boxes is controlled by the flex-direction property.
Possible values:
row - row (default); row-reverse - a row with elements in reverse order; column - column; column-reverse - a column with elements in reverse order.
row and row-reverse
column and column-reverse
Flex-wrap
There can be many blocks on one line. Whether or not they wrap is determined by the flex-wrap property.
Possible values:
nowrap - blocks are not wrapped (default); wrap - blocks are wrapped; wrap-reverse - blocks are wrapped and positioned in reverse order.
For shorthand, flex-direction and flex-wrap properties, there is a property: flex-flow.
Possible values: you can set both properties or only one. For example:
flex-flow: column; flex-flow: wrap-reverse; flex-flow: column-reverse wrap;
Demo for row-reverse wrap-reverse:
Order
The order property is used to control the order of blocks.
Possible values: numbers. To put the block first, give it order: -1:
Justify-content
There are several properties for aligning items: justify-content, align-items, and align-self.
justify-content and align-items apply to the parent container, align-self to children.
justify-content is responsible for aligning with the main axis.
Possible values \u200b\u200bfor justify-content:
flex-start - items are aligned from the start of the main axis (default); flex-end - items are aligned from the end of the main axis; center - items are aligned to the center of the main axis; space-between - elements are aligned along the main axis, distributing free space among themselves; space-around - items are aligned along the main axis, distributing free space around them.
flex-start and flex-end
space-between, space-around
Align-items
align-items is responsible for aligning the perpendicular axis.
Possible align-items values:
flex-start - items are aligned from the start of the perpendicular axis; flex-end - items are aligned from the end of the perpendicular axis; center - items are centered; baseline - elements are aligned to the baseline; stretch - The elements are stretched to fill all the space along the perpendicular axis (default).
flex-start, flex-end
baseline, stretch
Align-self
align-self is also responsible for perpendicular axis alignment, but is set to individual flex items.
Possible align-self values:
auto is the default. Means the element uses the align-items of the parent element; flex-start - the item is aligned from the start of the perpendicular axis; flex-end - the item is aligned from the end of the perpendicular axis; center - the element is centered; baseline - the element is aligned to the baseline; stretch - The element is stretched to fill the entire height.
Align-content
To control alignment within a multi-line flex container, there is an align-content property.
Possible values:
flex-start - items are aligned from the start of the main axis; flex-end - items are aligned from the end of the main axis; center - items are aligned to the center of the main axis; space-between - elements are aligned along the main axis, distributing free space among themselves; space-around - elements are aligned along the main axis, distributing free space around them; stretch - The elements stretch to fill their entire height (default).
flex-start, flex-end
center, stretch
space-between, space-around
Ps: Some things I have not been able to see in action, for example, the line flex-flow: column wrap or the complete record of the same flex-direction: column; flex-wrap: wrap; ...
Elements are stacked, but not carried:
Wrap does not fire when flex-direction: column; , although in spec it looks like this:
I think it will work over time.
UPD from 06/21/2014: everything works if you give the block a height. Thanks for the tip
Why Flexbox?
For a long time, the only reliable cross browser-compatible tools available for creating CSS layouts were things like floats and positioning. These are fine and they work, but in some ways they are also rather limiting and frustrating.
The following simple layout requirements are either difficult or impossible to achieve with such tools, in any kind of convenient, flexible way:
- Vertically centering a block of content inside its parent.
- Making all the children of a container take up an equal amount of the available width / height, regardless of how much width / height is available.
- Making all columns in a multiple column layout adopt the same height even if they contain a different amount of content.
As you "ll see in sections, flexbox makes a lot of subsequent layout tasks much easier. Let" s dig in!
Introducing a simple example
In this article we are going to get you to work through a series of exercises to help you understand how flexbox works. To get started, you should make a local copy of the first starter file - flexbox0.html from our github repo - load it in a modern browser (like Firefox or Chrome), and have a look at the code in your code editor. You can also.
Flex-direction: column;
You "ll see that this puts the items back in a column layout, much like they were before we added any CSS. Before you move on, delete this declaration from your example.
Note: You can also lay out flex items in a reverse direction using the row-reverse and column-reverse values. Experiment with these values \u200b\u200btoo!
Wrapping
One issue that arises when you have a fixed amount of width or height in your layout is that eventually your flexbox children will overflow their container, breaking the layout. Have a look at our flexbox-wrap0.html example, and try viewing it live (take a local copy of this file now if you want to follow along with this example):
Here we see that the children are indeed breaking out of their container. One way in which you can fix this is to add the following declaration to your element represents a standalone section - which doesn "t have a more specific semantic element to represent it contained within an html document.\u003e
Flex-wrap: wrap; flex: 200px;
Try this now; you "ll see that the layout looks much better with this included:
We now have multiple rows - as many flexbox children are fitted onto each row as makes sense, and any overflow is moved down to the next line. The flex: 200px declaration set on the articles means that each will be at least 200px wide; we "ll discuss this property in more detail later on. You might also notice that the last few children on the last row are each made wider so that the entire row is still filled.
But there "s more we can do here. First of all, try changing your flex-direction property value to row-reverse - now you" ll see that you still have your multiple row layout, but it starts from the opposite corner of the browser window and flows in reverse.
flex-flow shorthand
At this point it is worth noting that a shorthand exists for flex-direction and flex-wrap - flex-flow. So for example, you can replace
Flex-direction: row; flex-wrap: wrap;
Flex-flow: row wrap;
Flexible sizing of flex items
Let "s now return to our first example, and look at how we can control what proportion of space flex items take up. Fire up your local copy of flexbox0.html, or take a copy of flexbox1.html as a new starting point ( see it live).
First, add the following rule to the bottom of your CSS:
Article (flex: 1;)
This is a unitless proportion value that dictates how much of the available space along the main axis each flex item will take up. In this case, we are giving each element a value of 1, which means they will all take up an equal amount of the spare space left after things like padding and margin have been set. It is a proportion, meaning that giving each flex item a value of 400000 would have exactly the same effect.!}
Now add the following rule below the previous one:
Article: nth-of-type (3) (flex: 2;)
Section - article article article - div - button div button div button button button
Let "s look at the code we" ve used for the layout.
Summary
That concludes our tour of the basics of flexbox. We hope you had fun, and will have a good play around with it as you travel forward with your learning. Next we "ll have a look at another important aspect of CSS layouts - CSS Grids.
A modern front-end developer must actively be able to apply in practice various tools that allow automating the process of layout and programming of the client component of the project. For this, there are already many frameworks, both large and small, build systems, package managers, a whole bunch of packages for tasks of any level, preprocessors, templating tools and other "sugar", which was created to simplify and increase the productivity of a specialist in this field.
Unfortunately, it can be difficult for beginner fronts to understand the abundance of these tools, as they need to constantly develop and know the basics of layout. And for this reason, many continue to typeset "in an old-fashioned way", ordinary css, with a bunch of repeated selectors, layout without understanding the principle of different grids, wild headaches with various kinds of centering, etc.
If earlier, a million years ago, they were typesetting on tables, and then they climbed onto divas, now, without using flexbox in combination with grids or a ready-made css framework, I feel that even a simple layout on divas will soon be considered "bad manners". This is not yet the case, but as far as I observe (more precisely, I do not even have time to observe) the development of various techniques and best practices in this area, then most likely this option takes place.
Of course, in this small note, I will not be able to consider all the must-have skills of a good front and tools for comfortable work, but I will show and comment on some basic principles that allow you to push off and go further.
We make up adaptive
Let's start with responsive layout, as this is a very popular topic due to the rapid development of mobile traffic. In order to understand how various grids work, and therefore adaptive, let's look from the outside at the block elements that make up the page layout and act at the same time as containers for other elements (text, icons, pictures, etc., which can be placed by default or using positioning). Traditional layout on divs.
As you know, any display: block element by default occupies the entire available screen width, unless we explicitly define its width (either in px or in%). But even if the width defined in this way is set to it, then the next block element after it will come after it on a new line (this, by the way, differs block from inline, which will follow each other). This is an important point, you just need to understand it, and in order to understand it, it is easy to view this case in the inspector of any browser.
If we need the block elements to be adjacent to each other, then we need to wrap the elements (float), and we need to set the width of the blocks in% so that the browser automatically calculates the width in pixels. As a common example, this is a content block, and next to it is a sidebar. After wrapping the elements, remember to use clearfix, reset the wrapping, so as not to break the layout in the future.
The very first thing we need to do is to "notify" the browser that we want to use a responsive view, according to which any browser will open the page in this mode, this is done with the following declaration between the head tags of the document:
Meta name \u003d "viewport" content \u003d "width \u003d device-width, initial-scale \u003d 1"
In other words, the width of the device is at a scale of 1: 1. And if your layout is not made responsive, then most likely there will be problems with such a display in the mobile view (most likely all content will be compressed into an "accordion" if you logically imagine what could happen :). From now on, we can talk about the next step, which is in any grid system or responsive framework.
Any grid system has breakpoints, transition points. Let's look at Bootstrap, when, when changing the width of the screen (mobile, tablet view, etc.), an element is checked that has the current column class (for example, the desktop class for a column, in the popular Bootstrap framework, this is col-md- (x ), md - desktop). The classes, in turn, specify different widths in%, equal to (100/12) x, where x is the width factor, from 1 to 12.
Column classes describe the behavior of wrapping elements: there is a class (at the same time, the class can be for different devices) - the wrapping is set, no - the width is 100% (typical for presenting content on mobile devices). And this behavior is implemented using media queries that all browsers understand. Media request - in css, this concept means a rule, when the condition of which is met, the corresponding styles are connected, for example, the width has become less than 600px - we connect a new block of styles that overrides the old one. For example, the column class col-md- (x) is enabled by default from 992px and higher, and disabled until 992px. But all bootstrap breakpoints by default can be overridden by your own when compiling the grid.
That's all the simple mechanics with divs, which need to set the width in%, float: left; and clear the wrapping after the columns (in bootstrap, the columns are wrapped in a wrapper with the row class in this case), which we line up. All this can be easily implemented by yourself and without any grid, when there is a concept of how it works, just classes are written in any grid and a lot of code has already been written, your task remains to write classes to elements, that's all.
We will go a little further and consider another option. Using flexbox, at the same time in practice we will create a small skeleton of a responsive page using this new layout technology. In general, roughly speaking, flexes can save us from headaches such as centering, horizontal and vertical alignment in the container. And together with media queries, keeping in mind the mechanics described above, you can build a very high-quality adaptive template with any alignment, both vertically and horizontally. We play, in general, as we want.
Here I would like to note that the width specified in%, as in the case of the content area and the sidebar (the header and footer by default occupy the entire width, 100%), is automatically recalculated immediately upon resizing (or opening the page on a small screen). This is perhaps the main rule, set everything in%, the browser will do the rest itself.
In divas, let it be just text for now, let's practice aligning the text (horizontally / vertically). It is also good practice to exclude the footer from the general wrapper, set html and body, height: 100%, to the wrapper: min-height: 100%, so that the footer is always pressed to the bottom of the page.
I'm used to using scss, I will give a listing of the code on it:
$ gray: # 808080; $ h: 50px; html, body (margin: 0; height: 100%;) body (font-family: monospace, sans-serif; text-transform: uppercase;) .row (display: flex;) .vertical-center (align-items: center; justify-content: center;) .wrap (min-height: 100%; header, .content, .sidebar (border: 1px solid $ gray;) header (height: $ h;) .content (height: 100px; padding: 15px 15px 0 15px; border-top-width: 0; margin-right: 1%; width: 75%;) .sidebar (height: 120px; padding: 15px 15px 0 15px; border-top-width: 0; width: 25%;)) footer (height: $ h; border: 1px solid $ gray;)
display: flex; - incl. flex context property flex-direction: row; - by default, if we do not specify column explicitly. This is what allows us to do many amazing things. I'm not quite sure, but it seems that this property is not supported everywhere by caniuse, but it's time to throw out all these old browsers and install modern ones, right? :)
We also set the ratio for the width of the content - sidebar, 75%: 25%. The same effect would be obtained if using bootstrap. Only with classes col-md-9 for content ((100/12 9)% - width in percentage, 75) and col-md-3 for sidebar ((100/12 · 3)% - width in percentage, 25)
So let's figure out what's going on and how flexbox works. The very first thing is to set display: flex to the container in which we need to center, for example. In the markup, I have this header, footer and container, inside which is content and sidebar. The simplest thing that flexbox does efficiently here is to simply grab and align the text that is in the header and footer using the .vertical-center class:
.vertical-center (align-items: center; // align center, vertically justify-content: center; // align center, horizontally)
As a result, the text is aligned in two directions, in the header and footer. The middle part remains, here, if we did not set display: flex, then the default would remain display: block, which in the end with the content and sidebar blocks, it turned out like this:
Those. location one below the other. And it doesn't matter if they are given a width, they would have to wrap around. But that's not even the convenience of flexbox. Not to shorten the code by one instruction, but that with the help of a few more wonderful properties that we can set the flexbox, we can center blocks of different widths in two directions, as well as text (centered, vertically / horizontally, at the beginning, at the end)!
But before we get to that main question for which this post was created, let's make our simple layout a little more responsive. Now, when resizing, the content and sidebar do not stack under each other. It is necessary to fix this, because, imagine that all the text at low resolutions will be ugly "compressed" in the content area and sidebar. I'm not even talking about pictures. By the way, images that will be adaptive must be set:
img (display: block; max-width: 100%; height: auto;)
Let's use media queries. Improving our css, I will not rewrite it all, I will just leave // \u200b\u200b... * where the code is the same:
// .. $ mobileBreak: 479px; html, body (// ...) body (// ...) .row (// ...) .middle (@media (max-width: $ mobileBreak) (display: block;)) .vertical- center (// ...) .wrap (// ... header, .content, .sidebar (// ...) header (// ...) .content (// ... @media (max -width: $ mobileBreak) (width: auto; margin-right: 0;)) .sidebar (// ... @media (max-width: $ mobileBreak) (width: auto;))) footer (//. ..)
Now the sidebar will fold under the content on phones (<480px):
Working with alignments
As a test, let's create in the content block several balloons filled with different colors, so that they are aligned horizontally and vertically in the content area, for this we add html:
// ... $ mobileBreak: 479px; @mixin wh ($ w, $ h) (width: $ w; height: $ h;) // ... .content (// ... padding-top: 0; .content-inner (height: 100% ; justify-content: space-between; align-items: center; .bounce (-webkit-border-radius: 50%; -moz-border-radius: 50%; border-radius: 50%;) .red (background : # D9534F;) .green (background: # 6AB181;) .blue (background: # 2D8CD3;) .wh50 (@include wh (50px, 50px);) .wh60 (@include wh (60px, 60px);). wh35 (@include wh (35px, 35px);)) @media (max-width: $ mobileBreak) (// ...)) // ...
Again, where there are signs, // ..., the code remains the same.
Result:
As you can see, the balls are perfectly aligned. When adding new balls, the alignment will also occur without any problems. Align-items property: center; is responsible for vertical alignment, and justify-content: space-between; evenly horizontally.
align-items: flex-start; does like this:
By analogy, after applying align-items: flex-end; balls end up at the bottom of the container, and align-items: baseline; does like this:
There is also a property align-items: stretch;, it seems to stretch each element in height, but I didn't manage to quickly implement it, so I won't show the screen.
This is all related to the horizontal axis (default). But if we do column explicitly:
.content-inner (flex-direction: column;)
Then the balls will be vertical! And again, using various align-items properties, we will achieve everything that is in the case of horizontal construction of balls, but only vertically! There is also the align-self property, it overrides the align-items property for some one ball or group. In this way, you can flexibly manage all alignments.
In this short note, we looked at the basics of responsive layout, more precisely, the mechanics that allow elements on the page to adjust to different resolutions, and also looked at the basics of flexbox layout. I hope the article will be useful first of all to those who do not want, for example, to take the entire huge bootstrap for the sake of just one mesh, but will take and create their own, based on the materials of this lesson.
Finally, flexbox is cool, but you still need to use it carefully if you need support for older versions of browsers.
How easy it is to work with Flexbox using the example of layout of a news site template.
Trust me, there is no need for a detailed breakdown of all aspects of working with Flexbox if you want to start using it now. In this tutorial, I'm going to introduce you to some of the properties of Flexbox and make a "news layout" like the one you might have seen on The Guardian's website.
The reason the author uses Flexbox is because of the large number of features it provides:
- ease of creating responsive columns;
- creating columns of the same height;
- the ability to push the content to the bottom of the container.
Let's go!
1. Start by creating two columns
Creating columns with CSS has always been a challenge. For a long time, floats and / or tables have been (and are) widely used to accomplish this task, but each of these methods had (and has) its drawbacks.Flexbox, in turn, simplifies this process with a number of benefits such as:
Writing cleaner code: we just need to create a container with a rule display: flex;
- flexibility: we can resize, stretch and align columns by changing a couple of lines of CSS;
- semantic markup;
- in addition, with the use of Flexbox there is no need to cancel the wrapping to avoid unpredictable layout behavior.
Let's start by creating two columns, one of which will take up 2/3 of the width of our container, and another one will take up 1/3 of it.
There are two elements here:
Container columns;
- two children column, one of which has an additional class main-columnwhich we will use later to make the column wider.
Columns (display: flex;) .column (flex: 1;) .main-column (flex: 2;)
Insofar as main-column has a flex value of 2
, then this column will take up twice as much space as the second.
Let's add some visual design and, as a result, we get:
Click to see it in action
2. Make each column a flexbox container
Each of the two columns will contain several vertically arranged articles, so we, in turn, must also make flexbox containers out of these two elements.So, we need the articles:
Placed vertically inside the container column;
- occupied all available space.
The rule flex-direction: columnspecified for the container, along with the rule flex: 1, specified for the child element, allows the article to fill all the free space vertically, while the height of the first two columns remains unchanged.
Click to see it in action
3. Making a container from an article
Now, to further expand our capabilities, let's present each article as a flexbox container. Each such container will contain:Title;
- paragraph;
- information panel with the author's name and the number of comments;
- some adaptive image.
Here we are using Flexbox to "nip" the information bar to the bottom of the element. Here, see what result we expect to get.
And here is the code itself:
.article (display: flex; flex-direction: column; flex-basis: auto; / * Sets the initial size of the element based on its content * /) .article-body (display: flex; flex: 1; flex-direction: column;) .article-content (flex: 1; / * Content fills all remaining space, thereby pushing the info bar to the bottom * /)
Elements within an article are arranged vertically by using the rule flex-direction: column.
We also applied the property flex: 1 to element article-content, thereby stretching it to all the free space and pressing article-info to the bottom. The height of the columns does not matter in this case.
Click to see it in action
4. Add multiple nested columns
In fact, we want the left column to include a few more columns. Therefore, we need to replace the second element responsible for the article with a container columnswhich we used earlier.
Since we want the first nested column to be wider, add the class nested-column, and in CSS we will indicate:
Nested-column (flex: 2;)
This column will now be twice as wide as the second.
Click to see it in action
5. Making the first article with a horizontal layout
Our first article is really big. In order to effectively use the space on the monitor screen, let's change its orientation to horizontal.First-article (flex-direction: row;) .first-article .article-body (flex: 1;) .first-article .article-image (height: 300px; order: 2; padding-top: 0; width: 400px;)
Property order in this case it plays a big role because it allows you to change the order of HTML elements without changing the HTML markup. In fact, article-image in the code comes before the element article-bodybut acts as if standing after him.
Click to see it in action
6. Making an adaptive layout
Now everything looks as we wanted, albeit a little flattened. Let's fix this by adding some flexibility to our layout.One of the great things about Flexbox is that it is enough to remove the rule display: flex in the container in order to completely disable it (Flexbox), while the rest of its properties (such as align-items or flex) will remain working.
As a result, we can activate the responsive layout by using Flexbox only when needed.
So we're going to remove display: flex from selectors .columns and .columnby packing them into a media query instead:
@media screen and (min-width: 800px) (.columns, .column (display: flex;))
That's all! On screens with a low resolution, all articles will be stacked on top of each other, and on screens with a resolution of more than 800 pixels - in two columns.
7. Adding finishing touches
To make the layout look more attractive on large screens, let's add some CSS tweaks: @media screen and (min-width: 1000px) (.first-article (flex-direction: row;) .first-article .article-body (flex: 1;) .first-article .article-image (height: 300px ; order: 2; padding-top: 0; width: 400px;) .main-column (flex: 3;) .nested-column (flex: 2;))
The content of the first article is horizontally aligned with the text on the left and the picture on the right. Also, the main column is now wider (75%). The same goes for the nested column (66%).
And here is the final result!
Click to see it in action
Conclusion
Now you can see for yourself that you can use Flexbox in your projects without even delving into all its subtleties, and the created layout is a good example of this. At least, the author really hopes so.The Flexbox Layout module (Flexible Box) aims to provide a more efficient way of positioning, aligning and distributing free space between items in a container, even when their size is unknown in advance and / or dynamic (hence the word "flex").
The main idea behind flexible layouts is to give the container the ability to change the width / height (and order) of its items in order to best fill the available space (mainly to fit on all types and sizes of screens). A flexbox container expands items to fill free space or shrinks them to avoid overflow.
Most importantly, Flexbox is directional agnostic, unlike conventional layouts (boxes based on vertical positioning and inline elements based on horizontal positioning). While they work well enough, they lack the flexibility to support large or complex applications (especially when it comes to reorienting, resizing, stretching, shrinking, etc.).
Note. Flexbox is more suitable for application components and small layouts, whereas CSS Grid is more suited for larger layouts.
Basics and terminology
Since Flexbox is a whole module and not a separate property, it contains many different things, including a whole bunch of properties. Some of them are designed to be set to their container (the parent, known as a "flex container"), while others must be set to children (known as "flex items").
Whereas a conventional layout system is based on box and inline directions, Flexbox is based on "flex-flow directions". Please take a look at this figure from the spec to explain the basic idea behind Flexbox.
Basically, the elements will be located along main axis (from main-start to main-end) or transverse axis (from cross-start to cross-end).
Browser support
CSS Flexible Box Layout Module
Chrome for Android
The Blackberry browser, starting from version 10, supports the new syntax.
Properties for the container
Properties for elements
Properties for Parent (Flex Container)
display
Defines a flex container; string or block depends on the passed value. Includes flex context for all of its direct, children.
Container (display: flex; / * or inline-flex * /)
Please note that CSS columns do not affect the flex container.
flex-direction
Sets the main axis, thus determining the direction of the elements located in the container. Flexbox (besides the optional wrapper) is a unidirectional layout concept. Think of flex items primarily as horizontal rows or vertical columns.
Container (flex-direction: row | row-reverse | column | column-reverse;)
- row (default) - from left to right in ltr; from right to left in rtl;
- row-reverse - from right to left in ltr; from left to right in rtl;
- column - the same as row, only from top to bottom;
- column-reverse - the same as row-reverse, only from bottom to top;
flex-wrap
By default, items will try to fill only one line. You can change this behavior and allow elements to wrap to the next line, if necessary.
Container (flex-wrap: nowrap | wrap | wrap-reverse;)
- nowrap (default) - all flex items will be located on one line;
- wrap - flex items will be laid out on multiple lines, from top to bottom;
- wrap-reverse - flex items will be laid out on multiple lines, from bottom to top;
justify-content
Determines the alignment along the main axis. This helps to distribute the free space left after all fixed and non-fixed flex items have reached their maximum size. It also helps you maintain some control over the alignment of elements when they overflow the line.
Container (justify-content: flex-start | flex-end | center | space-between | space-around;)
- flex-start (default) - elements are pressed to the beginning of the line;
- flex-end - elements are pressed to the end of the line;
- center - elements are centered along the line;
- space-between - the elements are placed evenly on the line; the first element is at the beginning of the line, the last element is at the end of the line;
- space-around - elements are placed evenly on a line with the same space around them. Please note that visually the space is not the same, as all elements have the same space on both sides. The first element will have one unit of space on the side of the container, but two units between it and the next element, because the next element also has one unit on both sides.
align-items
This property determines how flex items behave along the cross axis on the current line. Think of it like oh, just for the transverse axis (perpendicular to the main axis).
Container (align-items: flex-start | flex-end | center | baseline | stretch;)
- flex-start - elements are placed at the beginning of the transverse axis;
- flex-end - elements are placed at the end of the transverse axis;
- center - elements are located in the center of the transverse axis;
- baseline - elements are aligned to the baseline;
- stretch (default) - stretched to fill the entire container (still respect min-width / max-width);
align-content
Note. This property has no effect when there is only one row of flex items.
Container (align-content: flex-start | flex-end | center | space-between | space-around | stretch;)
- flex-start - lines are located at the beginning of the container;
- flex-end - lines are located at the end of the container;
- center - lines are placed in the center of the container;
- space-between - lines are distributed evenly, the first line is at the beginning of the container, and the last line at the end;
- space-around - lines are distributed evenly, with the same distance between them;
- stretch (default) - lines stretch across the entire width to take up the remaining space;
Properties for children (flex items)
order
By default, all elements are arranged in their original order. However, the order property controls the order in which elements are arranged within the container.
Item (order:
flex-grow
The property determines the ability of the element to grow in size, if necessary. It takes a unitless value as a proportion, which determines how much free space inside the container the element should occupy.
If all items have flex-grow set to 1, then the free space inside the container will be evenly distributed among all items. If one of the elements has a value of 2, then the element will take up twice as much space as the others (at least it will try).
Item (flex-grow:
Negative numbers cannot be specified.
flex-basis
Determines the default size of the element before the remaining space is allocated. It can be length (20%, 5rem, etc.) or a keyword. The auto keyword means "look like my width or height property". The content keyword means "size is based on the content of the element" - this keyword is not well supported yet, so it's hard to test, and even harder to know what its siblings min-content, max-content and fit-content are doing.
Item (flex-basis:
If set to 0, the extra space around the content will not be counted. If set to auto, extra space will be allocated based on the value.
flex
This is shorthand for, and. The second and third parameters (flex-shrink and flex-basis) are optional. The default is 0 1 auto.
Item (flex: none | [<"flex-grow"> <"flex-shrink">? || <"flex-basis"> ] }
align-self
This property allows you to override the default (or property-set) alignment for individual flex items.
Please look at the explanation of the property to understand the available values.
Item (align-self: auto | flex-start | flex-end | center | baseline | stretch;) .item (align-self: auto | flex-start | flex-end | center | baseline | stretch;)
Note that float, clear, and vertical-align have no effect on the flex item.
Examples of
Let's start with the simplest example that solves a problem that occurs almost every day: perfect centering. It couldn't be easier if you're using Flexbox.
Parent (display: flex; height: 300px;) .child (width: 100px; height: 100px; margin: auto;)
It depends on the flex container's auto margin absorbing extra space. Thus, setting the vertical margin to auto on an element will make the element perfectly centered on both axes.
Now let's use a few more properties. Consider a list of 6 items, all aesthetically fixed size, but they can be automatic. We want them to be evenly spaced along the horizontal axis and to be fine when the browser is resized (no media queries!).
Flex-container (display: flex; flex-flow: row wrap; justify-content: space-around;)
Done! Everything else is just some design problem. Below is an example on CodePen, be sure to go there and try resizing the windows to see what happens.
Let's try something else. Imagine we have a right-aligned navigation at the very top of the screen, but we want it to be centered on medium-sized screens and in one column on small screens. Easy peasy.
Navigation (display: flex; flex-flow: row wrap; justify-content: flex-end;) @media all and (max-width: 800px) (.navigation (justify-content: space-around;)) @media all and (max-width: 500px) (.navigation (flex-direction: column;))
Let's try to do something even better by playing with the flexibility of our flex items! How about a three-column mobile-first layout with a full-width header and footer, and no dependence on the original order of the elements.
Wrapper (display: flex; flex-flow: row wrap;) .header, .main, .nav, .aside, .footer (flex: 1 100%;) @media all and (min-width: 600px) (.aside (flex: 1 auto;)) @media all and (min-width: 800px) (.main (flex: 2 0px;) .aside-1 (order: 1;) .main (order: 2;) .aside- 2 (order: 3;) .footer (order: 4;))
Related properties
Errors
Flexbox is definitely not without its bugs. The best collection I've seen comes from Philip Walton and Greg Whitworth's Flexbugs. This is an Open Source place to track all bugs, so I think it's best to just post a link.