Using flex-direction to layout content horizontally and vertically

Share this video with your friends

Social Share Links

Send Tweet

The Flexbox css spec allows for more adjustable layouts. The flex-direction property allows you to easily change the layout on the children of an element without making any changes to the dom, which is particularly useful when combined with media queries.

[00:01] Flexbox is a fairly new layout mode in CSS, and it gives us a lot of new properties that can be adjusted to output a wide variety of layouts.

[00:08] By default, content on a page flows vertically from top to bottom. In this example, we have an unordered list of links, similar to something that could be used as a web page navigation. I'm going to go ahead and remove the bullets from the list, by setting the list style to none on the unordered list. Then I'll set display to flex.

[00:27] Flex will leave this unordered list as a block level container, and will affect the layout of its children. If I wanted the container to be an inline element, but also wanted the contents to be displayed using flexbox, I could change display to inline flex.

[00:42] Both flex and inline flex will lay out the children the same. But flex makes the container a block element, breaking the horizontal flow with its siblings, and inline flex, like an image tag, will not.

[00:55] Notice when I added display flex, that the links changed orientation to be laid out horizontally. That's because flexbox containers have a property called flex direction, which defaults to row, which, like the rows of a table, are laid out horizontally.

[01:09] I can change it back to a vertical layout by changing flex direction to column. Additionally, I have two alternative layouts which affect the order of the children. Column reverse will cause the children to flow from bottom to top, and row reverse will lay them out from left to right.

[01:25] Flex direction is most useful in the context of a responsive web design. When combined with media queries, it can adjust the layout direction of the children based on the size of the window.

[01:37] Currently, I'm working on a website that has a horizontal navigation. But when the window size is closer to a mobile screen, the navigation is laid out in a vertical list to make better use of the screen real estate.

[01:49] It is important to note that many flexbox properties, including flex direction, need prefixes for some browsers. Make sure to double check documentation, or better yet, use the auto prefixer post CSS tool to automatically add the needed prefixes.