MakeW3web

Flexbox basics

Flexbox is a layout model in CSS that allows you to easily create flexible and responsive layouts. It uses a set of properties that allow you to control the alignment, distribution, and ordering of elements within a container.

Creating a Flexbox Container

To create a Flexbox container, you need to set the `display` property of the container to `flex`. Here's an example:

HTML:

<div class="container">
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
</div>

CSS:

.container {
  display: flex;
}

In this example, the `.container` element is set to `display: flex`, which makes it a Flexbox container. The three `.item` elements inside the container will automatically become Flexbox items.

Controlling Flexbox Items

Once you've created a Flexbox container, you can control the layout of the items inside it using a variety of properties. Here are some of the most commonly used Flexbox properties:

`flex-direction`

This property determines the direction of the main axis, which is the primary axis along which Flexbox items are laid out. The default value is `row`, which lays out items horizontally. Other options include `column` (lays out items vertically), `row-reverse`, and `column-reverse`.

.container {
  display: flex;
  flex-direction: column;
}

`justify-content`

This property controls the alignment of items along the main axis. It allows you to distribute items evenly or align them to one end or the other. Options include `flex-start`, `flex-end`, `center`, `space-between`, `space-around`, and `space-evenly`.

.container {
  display: flex;
  justify-content: center;
}

`align-items`

This property controls the alignment of items along the cross axis, which is perpendicular to the main axis. It allows you to align items to the top, middle, or bottom of the container. Options include `flex-start`, `flex-end`, `center`, `baseline`, and `stretch`.

.container {
  display: flex;
  align-items: center;
}

`flex-grow`

This property determines how much a Flexbox item should grow to fill any available space in the container. The default value is `0`, which means items will not grow. Setting it to a positive value will cause items to grow proportionally to their flex grow value.

.item {
  flex-grow: 1;
}

Conclusion

Flexbox is a powerful and flexible layout model in CSS that can make creating responsive layouts much easier. By using the properties outlined above, you can create complex and dynamic layouts with minimal CSS code.

Was this page helpful?