flex-basis defines the initial size of a flex item before any space distribution takes place. In simpler terms, it sets the starting size of a flex item along the main axis (which is determined by the flex-direction property) before any available space is distributed among the flex items. It acts as a base size from which the flex item can grow or shrink.
The flex-basis property can take different values:
1. Length values: This could be any valid CSS length unit, such as px, em, rem, vw, %, etc.
2. Content-based value: The keyword auto tells the browser to calculate the size based on the content of the flex item, similar to setting width or height to auto.
3. Zero (0): This makes the flex item start with no width, and then space is distributed based on other flex properties like flex-grow and flex-shrink.
How flex-basis Works?
1. When you set flex-basis to a specific length, it will assign that length to the item along the main axis.
2. If the combined size of all flex items (including flex-basis values) is less than the container size, the remaining space will be distributed according to the flex-grow property.
3. If the combined size is greater than the container size, the flex-shrink property will decide how items should shrink to fit.
flex-basis.html
<!DOCTYPE html> <html> <head> <style> .container { display: flex; width: 600px; /* Total width of the container */ border: 2px solid #000; margin-top: 10px; } .item { flex-grow: 1; /* Items will grow equally if space is available */ flex-shrink: 1; /* Items will shrink equally if needed */ border: 2px solid red; } .item1 { flex-basis: 100px; /* Item 1 starts with a width of 100px */ } .item2 { flex-basis: 200px; /* Item 2 starts with a width of 200px */ } .item3 { flex-basis: 150px; /* Item 3 starts with a width of 150px */ } </style> </head> <body> <div class="container"> <div class="item item1">Item 1</div> <div class="item item2">Item 2</div> <div class="item item3">Item 3</div> </div> </body> </html>
Explanation
· The container is 600px wide.
· The flex-basis property is set on each item:
a. Item 1 starts with a width of 100px.
b. Item 2 starts with a width of 200px.
c. Item 3 starts with a width of 150px.
· The combined starting widths are 100px + 200px + 150px = 450px.
· Since the total width of the container (600px) is larger than the combined starting widths (450px), there is extra space (600px - 450px = 150px).
· The remaining space (150px) will be distributed equally among the three items due to the flex-grow: 1 property set on each item.
a. Each item will grow by an additional 50px (150px / 3).
Thus, the final widths of the items will be:
· Item 1: 100px (initial) + 50px (extra) = 150px
· Item 2: 200px (initial) + 50px (extra) = 250px
· Item 3: 150px (initial) + 50px (extra) = 200px
No comments:
Post a Comment