0
0
CSSmarkup~5 mins

Flex direction in CSS

Choose your learning style9 modes available
Introduction

Flex direction tells the browser how to arrange items inside a container. It helps decide if items go side by side or stacked up.

When you want items in a row, like buttons in a toolbar.
When you want items stacked in a column, like a list of menu links.
When you want to change the order of items visually without changing the HTML.
When you want a layout that adapts for mobile screens by switching direction.
When you want to create a navigation bar that can switch between horizontal and vertical.
Syntax
CSS
flex-direction: row | row-reverse | column | column-reverse;
row arranges items left to right (default).
column stacks items top to bottom.
Examples
Items line up side by side from left to right.
CSS
flex-direction: row;
Items stack vertically from top to bottom.
CSS
flex-direction: column;
Items line up side by side but in reverse order, right to left.
CSS
flex-direction: row-reverse;
Items stack vertically but from bottom to top.
CSS
flex-direction: column-reverse;
Sample Program

This example shows a container with three items stacked vertically because flex-direction: column; is used. The container has a border and spacing between items for clarity.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Flex Direction Example</title>
<style>
  .container {
    display: flex;
    flex-direction: column;
    gap: 1rem;
    border: 2px solid #333;
    padding: 1rem;
    width: 200px;
  }
  .item {
    background-color: #4a90e2;
    color: white;
    padding: 0.5rem;
    text-align: center;
    border-radius: 0.25rem;
    font-family: Arial, sans-serif;
  }
</style>
</head>
<body>
  <section class="container" aria-label="Flex direction container">
    <div class="item">Item 1</div>
    <div class="item">Item 2</div>
    <div class="item">Item 3</div>
  </section>
</body>
</html>
OutputSuccess
Important Notes

Remember to set display: flex; on the container before using flex-direction.

Using flex-direction changes the main axis, which affects how other flex properties behave.

For accessibility, use semantic HTML and ARIA labels to describe the container's role.

Summary

flex-direction controls how flex items are laid out: in a row or column, normal or reversed.

It works only when display: flex; is set on the container.

Changing direction helps create flexible and responsive layouts easily.