Tuesday, 28 January 2025

Understanding the flex-shrink Property with Real-World Examples

What is flex-shrink?

The flex-shrink property in CSS is used to define the ability of a flex item to shrink if necessary. It determines how much a flex item will shrink relative to the other items inside the same flex container when there is not enough space. By default, the flex-shrink property is set to 1, which means the item will shrink to fit the container. If you set it to 0, the item will not shrink, and if you set it to a higher number, the item will shrink more compared to others with a lower flex-shrink value.

 

How Does flex-shrink Work?

When you have a flex container with multiple flex items inside, and the total width (or height, depending on the flex direction) of the items is greater than the container's size, the flex-shrink property comes into play. It defines how much each item should shrink in proportion to the other items.

 

Syntax

.item {
flex-shrink: <number>;
}

<number>: This is a number that acts as a proportion. It can be 0, 1, 2, etc., and it indicates how much the flex item should shrink relative to other flex items.

 

flex-shrink.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flex Grow Example</title>
    <style>
        .container {
            display: flex;
            width: 90vw;
            margin: 20px;
            background-color: black;
        }

        .item {
            flex-basis: 300px; /* Default size of each item */
            flex-shrink: 1;    /* Default shrink value */
            background-color: lightblue;
            text-align: center;
            border: 1px solid red;
        }

        .item1 {
            flex-shrink: 1;
        }

        .item2 {
            flex-shrink: 2;
        }

        .item3 {
            flex-shrink: 3;
        }


    </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>


 

Try to shrink the page, you can observe that Item 3 shrink more than Item 2 and Item 2 shrinks more than Item 1.

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment