CSS Flexbox

CSS Flexbox, otherwise known as the Flexible Box Layout, is an advanced layout model that enables space to be distributed across one dimension, either horizontally or vertically. It is a much simpler and flexible way of laying out pages and aligning space among items in a container, while also with unknown or dynamic dimensions.

Why Use Flexbox?

Flexbox is one of the most commonly used layout options in modern web development for many reasons. Flexbox allows for:

Basic Structure of Flexbox

Flexbox consists of a flex container and the flex items inside it. The container is defined by setting display: flex; (or display: inline-flex; for inline layouts) on the parent element. These items are placed automatically based on what you define to the container and the children.

Basic Example


          .container {
              display: flex;
          }

          .item {
              flex: 1;
          }

In this example, all the .item elements within the .container will be distributed evenly across the container's width and share the same amount of space.

Flexbox Properties

1. Flex Container Properties

There are several key properties that you can apply to the flex container:

2. Flex Item Properties

The individual items in a flex container can also have their own unique properties:

Example: Simple Flexbox Layout

Here’s an example of how to create a simple flexbox layout with three items:


          .container {
               display: flex;
               justify-content: space-between;
               align-items: center;
          }

          .item {
               background-color: #4CAF50;
               color: white;
               padding: 20px;
               margin: 10px;
          }
     
Item 1
Item 2
Item 3

Best Practices for Using Flexbox

Conclusion

Flexbox gives web developers a lot of new options for working with layout today. The options it gives you for aligning items, sharing space, and letting the layout respond makes it an essential tool for modern web development. Using its simple power is central to creating modern, flexible, responsive web projects.

Try it Yourself