CSS flex basis
Created By: chatGPT
Flex-basis is a property used in CSS Flexbox that defines the initial size of a flex item before any available space is distributed. It can be seen as the starting point or the base size of a flex item along the main axis. This means that if you set
flex-basis
for an item, it will occupy that much space initially and then the flex-grow and flex-shrink properties can adjust it as needed./* Example of using flex-basis in a flex container */
.container {
display: flex;
}
.item {
flex-basis: 200px; /* Each item starts with a base size of 200px */
flex-grow: 1; /* Items can grow to fill the available space */
flex-shrink: 1; /* Items can shrink if necessary */
}
You can set flex-basis using specific units such as pixels, percentages, or even keywords like
auto
. When set to auto
, the width (or height) of the item will be its intrinsic size. If the flex container has a defined width, you can define how the items behave in that space effectively./* Flexible items with flex-basis set to auto */
.container {
display: flex;
}
.item {
flex-basis: auto; /* Will take the intrinsic width of the element */
flex-grow: 1;
flex-shrink: 1;
}
When using flex-basis, it's important to know that it can be combined with
flex-grow
and flex-shrink
to create a responsive and flexible layout. This makes it easier to manage how items resize relative to each other as the size of the flex container changes./* Example showing a responsive flex layout */
.container {
display: flex;
width: 100%;
}
.item {
flex-basis: 300px;
flex-grow: 2; /* This item can grow twice as much as the others */
flex-shrink: 1; /* This item will shrink if needed */
}
.item:nth-child(2) {
flex-grow: 1; /* This item has a lower growth rate */
}