CSS

Control Flex Item Sizing with flex-grow, flex-shrink, and flex-basis

Understand `flex-grow`, `flex-shrink`, and `flex-basis` to create dynamic and flexible item sizing within a Flexbox container for adaptive UIs.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flex Item Sizing</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="flex-container">
        <div class="flex-item item-1">Item 1 (grow: 1, shrink: 1, basis: 100px)</div>
        <div class="flex-item item-2">Item 2 (grow: 2, shrink: 0, basis: 150px)</div>
        <div class="flex-item item-3">Item 3 (grow: 0, shrink: 1, basis: 200px)</div>
    </div>
    <p>Resize your browser window to see how items adapt.</p>
</body>
</html>

body {
    font-family: sans-serif;
    margin: 20px;
    background-color: #f4f4f4;
}

.flex-container {
    display: flex;
    border: 2px solid #333;
    padding: 10px;
    background-color: #fff;
    min-height: 150px;
    justify-content: space-around; /* Distribute items evenly */
    align-items: center; /* Vertically center items */
    flex-wrap: wrap; /* Allow items to wrap to next line if needed */
    gap: 10px; /* Space between items */
}

.flex-item {
    padding: 15px;
    background-color: #007bff;
    color: white;
    text-align: center;
    border-radius: 5px;
    box-sizing: border-box; /* Include padding/border in width calculation */
    min-width: 80px; /* Ensure items don't get too small */
}

.item-1 {
    flex: 1 1 100px; /* flex-grow: 1, flex-shrink: 1, flex-basis: 100px */
    background-color: #28a745;
}

.item-2 {
    flex: 2 0 150px; /* flex-grow: 2, flex-shrink: 0, flex-basis: 150px */
    background-color: #ffc107;
    color: #333;
}

.item-3 {
    flex: 0 1 200px; /* flex-grow: 0, flex-shrink: 1, flex-basis: 200px */
    background-color: #dc3545;
}
How it works: This snippet demonstrates the powerful `flex` shorthand property, which combines `flex-grow`, `flex-shrink`, and `flex-basis`. `flex-basis` defines the initial size of a flex item before any growing or shrinking occurs. `flex-grow` dictates how much an item will grow relative to other items when there's extra space in the container. `flex-shrink` determines how much an item will shrink relative to others if the container is too small. By adjusting these values, you can create highly dynamic and responsive layouts where items intelligently distribute space based on their importance or desired behavior. For instance, `item-2` has `flex-grow: 2`, making it grow twice as fast as `item-1`. `item-3` has `flex-grow: 0`, so it won't grow beyond its `flex-basis` size.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs