How to Use flex-basis in CSS: Syntax and Examples
flex-basis property in CSS sets the initial main size of a flex item before any remaining space is distributed. It accepts length values like px, %, or auto, defining how much space the item should take along the flex container's main axis.Syntax
The flex-basis property defines the starting size of a flex item before the flex container distributes extra space. It works along the main axis (horizontal or vertical depending on flex-direction).
- auto: The item sizes itself based on its content or width/height.
- length: A fixed size like
100px,20%, or10rem. - content: (Newer) Sizes based on content size.
flex-basis: <length> | auto | content;
Example
This example shows three flex items with different flex-basis values. The first item starts at 100px wide, the second at 50%, and the third uses auto to size based on content.
html, body {
height: 100%;
margin: 0;
}
.container {
display: flex;
border: 2px solid #444;
padding: 10px;
gap: 10px;
}
.item {
background-color: #8ac6d1;
color: #fff;
padding: 20px;
font-weight: bold;
text-align: center;
}
.item1 {
flex-basis: 100px;
}
.item2 {
flex-basis: 50%;
}
.item3 {
flex-basis: auto;
}Common Pitfalls
One common mistake is confusing flex-basis with width or height. flex-basis sets the initial size along the main axis in a flex container, which may be horizontal or vertical. Also, setting flex-basis to auto means the item sizes itself based on content or width/height, so if you want a fixed size, use a length value.
Another pitfall is forgetting that flex-grow and flex-shrink can override the size set by flex-basis when the container space changes.
/* Wrong: Using width instead of flex-basis in flex container */ .container { display: flex; } .item { width: 100px; /* This may be overridden by flex properties */ flex-grow: 1; } /* Right: Use flex-basis to set initial size */ .item { flex-basis: 100px; flex-grow: 1; }
Quick Reference
- flex-basis: Sets the initial size of a flex item along the main axis.
- Accepts
auto, fixed lengths (px,%,rem), orcontent. - Works with
flex-growandflex-shrinkto adjust size dynamically. - Overrides
widthorheightin flex context.
Key Takeaways
flex-basis to set the starting size of a flex item along the main axis.flex-basis accepts fixed sizes like 100px or relative sizes like 50%.flex-grow and flex-shrink can change the final size beyond flex-basis.flex-basis with width or height in flex containers.auto for flex-basis to size items based on their content.