使用 Flexbox,子元素默认会根据最宽的元素调整大小。
是否有某种方法可以定义特定的子级将控制宽度,即使它更小?也许用选择器?
代码笔:https://codepen.io/dsomekh/pen/rwEYYE
代码:
.center {
display: flex;
align-items: center;
justify-content: center;
}
.first {
border: 1px solid red;
margin-bottom: 0.5vw;
}
.second {
border: 1px solid red;
}
.wrapper {
font-family: Calibri;
display: flex;
flex-direction: column;
}
<html>
<div class="center">
<div class="wrapper">
<div class="first">This DIV is bigger. However, can it shrink according to it's brother?</div>
<div class="second">This div is smaller.Can it control the width?</div>
</div>
</div>
</html>
最佳答案
以下是需要了解的重要 CSS 规则:
flex: {number} {number} {number}
;
第三个数字是 flex 元素的默认大小(宽度,如果 flex 元素位于一行中)。默认情况下,它是auto
,这意味着 flex 元素的默认大小由其内容决定。
如果沿主轴有空间,第一个和第二个数字分别是与其他 Flex 元素相比可以按比例增长或缩小的量(同样,如果该 Flex 元素位于一行,则为宽度)。
因此,您不能将 flex 元素的默认大小设置为相对于同级元素的固有大小(即由其内容决定的大小),但您可以设置 flex 元素的默认大小flex-item(及其同级元素)全部相同,并让它们增长或缩小。
我发现自己经常做以下事情:
flex :1 0 0
在 flex 元素上,这会导致同级元素的大小相同。
所有 flex 元素都以默认大小 0 开始,并且它们都均匀增长 - 正如所有 flex 元素的第一个数字相同(这里是一个,但它可以是任何正数,只要对于每个 sibling 来说都是一样的)-因为他们需要这样做。
最好的 Flexbox 学习在这里:https://css-tricks.com/snippets/css/a-guide-to-flexbox/
编辑
如果您事先知道哪个元素本质上会更大,您可能可以通过将该元素设置为 flex: 0 0 auto
并让所有其他 flex 元素从flex: 1 0 0
,但我有一种感觉,你事先并不知道哪个更大。
.wrapper { display: flex; }
.wrapper>div { border: 1px solid #000; }
.first { flex: 1 0 0; }
.second { flex: 0 1 auto; }
<div class="center">
<div class="wrapper">
<div class="first">This DIV is bigger. However, can it shrink according to it's brother?</div>
<div class="second">This div is smaller.Can it control the width?</div>
</div>
</div>
关于html - FlexBox - 指定某个子div来控制宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45190796/