Introduction to CSS Flexbox

Flexbox (Flexible Box Layout) is a CSS layout model that allows you to organize elements within a container efficiently and flexibly. It is especially useful for creating responsive designs and aligning elements in one direction (row or column) so they adapt to different screen sizes.

Published on September 25, 2023

Views
100 views
Reading time:
Reading time: 2 min

Flexbox

##What is Flexbox?

Flexbox (Flexible Box Layout) is a CSS layout model that allows you to organize elements within a container efficiently and flexibly. It is especially useful for creating responsive designs and aligning elements in one direction (row or column) so they adapt to different screen sizes.

HTML structure example:

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

##Basic Flexbox Setup

To use Flexbox, you first need to define a flex container using the display: flex property. The elements inside this container will become flex items.

CSS example:

.container {
  display: flex;
}
.item {
  width: 100px;
  height: 100px;
  background-color: #3498db;
  margin: 10px;
}

##Element Alignment

The justify-content and align-items properties are essential for aligning elements within the flex container.

CSS example:

.container {
  display: flex;
  justify-content: center; /* Centrar horizontalmente */
  align-items: center; /* Centrar verticalmente */
}

##Element Order

The order property allows you to change the visual order of flex items without modifying the order in the HTML code.

CSS example:

.item:nth-child(2) {
  order: 1; /* Cambiar el orden del segundo elemento */
}

##Spacing Between Elements

To control the space between flex items, you can use the justify-content and align-content properties.

CSS example:

.container {
  display: flex;
  justify-content: space-between; /* Espacio entre elementos */
  align-content: center; /* Centrar verticalmente */
}

##Element Sizing

The flex-grow, flex-shrink, and flex-basis properties allow you to control the size of flex items.

CSS example:

.item {
  flex: 1 0 200px; /* Crecer, no encoger, tamaño base de 200px */
}

This article provides a solid introduction to Flexbox with detailed code examples.