防止软盒缩水

因为 在成长的行为是有用的,所以我使用 Flexbox 来布局一个页面。但我想完全阻止 缩小的行为。

不管怎样,管理这个?

Example code:

<div class="flex-vertical-container">
<div class="flex-box">
This one should grow but not shrink
</div>
<div></div>
<div></div>
</div>

CSS

.flex-vertical-container {
display: flex;
flex-direction: column;
}


.flex-box {
flex: 1;
}
104760 次浏览

尝试在 .flex-box上将 flex-shrink属性设置为 0

Add a min-width with whatever you want the smallest possible value of the box to be. Flexbox won't shrink the width below the min-width.

你可以尝试向孩子申请:

.flex-box{
width: max-content;
}

最终结果:

.flex-vertical-container{
display: flex;
flex-direction: column;
}
.flex-vertical-container div{
background: gray;
}
.flex-box{
width: max-content;
}
<div class="flex-vertical-container">
<div class="flex-box">
This one should grow but not shrink
</div>
<div>This is shrinking</div>
<div>This is shrinking</div>
</div>


如果像我一样你的 flex-directionrow,尝试设置宽度的孩子为100% 。帮我治好了心理疾病。

Flex-shrink不适合我。

我最后在孩子们身上用了 white-space: nowrap;

This won't work for all cases, but if the children of your flex parent are one-liners of text, it just might.


(如果使用 TailwindCSS: whitespace-nowrap)

有两种防止收缩 灵活的孩子的变体

set to 灵活的孩子 this prop:

  1. 明确支持 flex-shrink: 0;
  2. 或者用简写 弯曲道具 flex: 1 0; /* Two values syntax: flex-grow | flex-basis */

In your case 灵活的孩子 is .flex-box

flex-wrap: wrap;成功了 Https://jsbin.com/zajojanamo/8/edit?html,css,output

main {
width: 200px;
height: 200px;
background: green;
display: flex;
flex-wrap: wrap;
}


div {
box-sizing: border-box;
border: 4px solid;
padding: 16px;
width: 50%;
background: lightblue;
}
<main>
<div>a</div>
<div>b</div>
<div>c</div>
<div>d</div>
</main>

There are already great answers here. The one that worked for me was min-width property on child element and flex-wrap to parent element.

下面是工作演示。你会注意到橙色的孩子有固定的最小宽度为240px,它可以展开,但不会低于240px。

body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}


.container {
display: flex;
flex-wrap: wrap;
padding: 20px;
background-color: #e1eaf4;
}


.child {
margin: 4px 8px;
padding: 12px 0;
border-radius: 4px;
outline: 4px solid #fff;
background-color: #3794fe;
color: #fff;
text-align: center;
}


.child:nth-child(1) {
flex-grow: 1;
}


.child:nth-child(2) {
flex-grow: 1;
min-width: 240px;
background-color: #e47f0b;
}


.child:nth-child(3) {
flex-grow: 1;
}
<div class="container">
<div class="child">
<p>Child 1</p>
</div>
<div class="child">
<p>Child 2</p>
</div>
<div class="child">
<p>Child 3</p>
</div>
</div>