简体   繁体   中英

How do I get flex-shrink to actually shrink an item?

I have a simple flex-box layout and I would like the middle item to shrink right down, but I cannot get any situation where the flex-shrink property works.

I've tried removing the flex-wrap property on the flex-container and changed the values of the flex items, but it still doesn't work?

In the code below, how do I get the middle div to shrink to a flex-shrink value of 10 like the code would suggest it should do?

Many thanks in advance for any help.

 body { padding: 20px; font-family: arial; } p { color: white; } .container { background-color: #666; max-width: 800px; height: 800px; margin: 0 auto; display: flex; flex-wrap: wrap; justify-content: center; } .item { padding: 10px; box-sizing: border-box; } .item1 { flex: 1 1 0; background-color: red; min-width: 200px; } .item2 { flex: 2 10 0; background-color: blue; } .item3 { flex: 1 1 0; background-color: green; } 
 <section class="container"> <div class="item item1"> <h1>ITEM1</h1> </div> <div class="item item2"> <h1>ITEM2</h1> </div> <div class="item item3"> <h1>ITEM3</h1> <p> - this is the third item with more content</p> </div> </section> 

https://codepen.io/emilychews/pen/rYeoza

That's not how flex-shrink works.

The job of flex-shrink is to distribute negative free space in the container among items. This means it will shrink items proportionally when the items would otherwise overflow the container.

But there is no overflow condition in your container.

The first column ( .item1 ) is 200px in width.

Your second column ( .item2 ) has no fixed width. It is set to consume free space.

Your third column ( .item3 ) has no fixed width. It is also set to consume free space.

Therefore, flex-shrink has nothing to do. In a container with width: 800px , where only 200px is used, flex-shrink is never called into action.

You have flex-shrink enabled on your three columns (with values 1, 10 and 1, respectively). If you disable flex-shrink on all of them you'll notice that it makes no difference to the layout.

Here's your demo with flex-shrink: 0 applied to all three times: revised codepen

For a detailed explanation of how flex-shrink works, see this post:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM