Flexbox is a CSS module that helps us arrange elements in a container in a flexible and easily adjustable way. Child elements in the container can be arranged horizontally or vertically and can expand or shrink depending on the remaining space.
Build a container
First, we need to define a container to hold the child elements. To do this, we will use the display: flex; property for the container.
.container {
display: flex;
}
Determine the size of child elements
Next, we need to define the initial size of child elements in the container. To do this, we use the flex-basis property to specify the initial size and the flex-grow property to determine the expansion ratio of child elements compared to other siblings.
.item {
flex-basis: 200px; /* Kích thước ban đầu của mỗi phần tử con */
flex-grow: 1; /* Tỉ lệ mở rộng của các phần tử con */
}
Determine the expansion and contraction of child elements
To make child elements expand or contract depending on the remaining space, we use the flex-shrink property. If we want the child elements to never contract, we can set the value of this property to 0.
.item {
flex-shrink: 1; /* Tỉ lệ co lại của các phần tử con */
}
Arrange child elements horizontally or vertically
By default, child elements are arranged horizontally. However, we can change them to be arranged vertically by using the flex-direction property with the value of column.
.container {
flex-direction: column; /* Xếp các phần tử con theo hàng dọc */
}
Divide child elements into multiple rows
If there is not enough space to display all child elements in a single row, we can wrap them into multiple lines by using the flex-wrap property with the value of wrap.
.container {
flex-wrap: wrap; /* Chia các phần tử con thành nhiều dòng */
}
Arrange child elements in reverse order
If we want to arrange child elements in reverse order, we can use the flex-direction property with the value of row-reverse to arrange child elements from right to left or column-reverse to arrange child elements from bottom to top.
.container {
flex-direction: row-reverse; /* Sắp xếp các phần tử con từ phải sang trái */
}
Flex CSS consists of 3 consecutive properties, namely flex-grow, flex-shrink, flex-basic
.item{
flex: 1 2 200px
}
In the example above, flex will have the following values:
Here is an example of using the flex property to create a responsive layout:
HTML
<div class="container">
<div class="item">Phần tử 1</div>
<div class="item">Phần tử 2</div>
<div class="item">Phần tử 3</div>
</div>
CSS
.container {
display: flex;
flex-wrap: wrap;
}
.item {
flex-basis: 200px;
flex-grow: 1;
flex-shrink: 1;
}
In the example above, child elements in the container will automatically expand and contract depending on the remaining space. The initial size of the child elements is 200px and they will be arranged in multiple rows when there is not enough space.