Sobes.tech
Junior

What is the purpose of flex in CSS?

sobes.tech AI

Answer from AI

Flexbox is used for creating one-dimensional layouts of elements within a container. It allows managing alignment, space distribution, and order of elements.

Main concepts:

  • Flex Container: The parent element assigned display: flex or display: inline-flex.
  • Flex Items: Child elements of the Flex Container.
  • Main Axis: The primary axis of the Flex Container. Defined by the flex-direction property. Default is horizontal (row).
  • Cross Axis: The perpendicular axis to the Main Axis.

Key properties for Flex Container:

  • display: Defines the element as a flex container (flex or inline-flex).
  • flex-direction: Sets the direction of the main axis (row, row-reverse, column, column-reverse).
  • justify-content: Aligns flex items along the main axis (flex-start, flex-end, center, space-between, space-around, space-evenly).
  • align-items: Aligns flex items along the cross axis (flex-start, flex-end, center, baseline, stretch).
  • flex-wrap: Determines whether flex items should wrap onto a new line/column when space is insufficient (nowrap, wrap, wrap-reverse).

Key properties for Flex Items:

  • order: Sets the visual order of the flex item (default 0).
  • flex-grow: Determines how much the flex item can grow relative to others (default 0).
  • flex-shrink: Determines how much the flex item can shrink relative to others (default 1).
  • flex-basis: Sets the initial size of the flex item before free space is distributed (default auto).
  • align-self: Overrides the alignment of the flex item along the cross axis for individual items.

Example usage:

.container {
  display: flex;
  justify-content: center; /* Center along main axis */
  align-items: center; /* Center along cross axis */
  height: 200px;
  border: 1px solid black;
}

.item {
  width: 50px;
  height: 50px;
  background-color: lightblue;
  margin: 5px;
}
<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

This makes it easy to center elements, create responsive grids, and control spacing between elements.

What is the purpose of flex in CSS? — Frontend - sobes.tech