我有以下HTML和CSS:
.box-1 {
background: #e51400;
}
.box-2 {
background: #fa6800;
}
.box-3 {
background: #f0a30a;
}
.box-4 {background: #e3c800; }
.box-5 {background: #a4c400;}
.box-6 {background: #60a917;}
.box-7 {background: #00aba9;}
.box-8 {background: #1ba1e2;}
.box-9 {background: #aa00ff;}
.container {
display: flex;
border: 8px solid black;
height: 500px;
display: flex;
flex-direction: column;
}
.box {
font-size: 50px;
color: white;
text-align:center;
font-family: lato;
font-weight: 300;
box-sizing: border-box;
width: 300px;
}
<section class="container">
<div class="box box-1">1</div>
<div class="box box-2">2</div>
<div class="box box-3">3</div>
<div class="box box-4">4</div>
<div class="box box-5">5</div>
<div class="box box-6">6</div>
<div class="box box-7">7</div>
<div class="box box-8">8</div>
<div class="box box-9">9</div>
</section>
当我们在flex-items上设置flex-direction: row
(默认值)和width
时,它们会在父元素本身中收缩,所以现在它们的宽度不是300px,它们会尝试收缩以适应父元素的宽度,因为flex-shrink
属性在flexbox中默认值为1。
但是当我把flex-direction: row
改为flex-direction: column
那么伸缩项目将离开父节点的height
。为什么?
你有9个高度为60px的.box
元素,试图适应高度为500px的.container
。
如果你做数学计算:9*60px = 540px,这比你的.container
的高度大。
你的.box
的内容没有缩小,因为你设置了一个font-size: 50px
和总行高使它60px。这是因为CSS的line-height
属性在默认情况下是110%或120%,这取决于你的浏览器
在本例中,元素的总高度为
font-size * line-height => 50px * 1.2 => 60px
这不是你的.box
中的一个空闲空间,flexbox将能够缩小以适应你的容器中的盒子。
如前所述,我建议您阅读有关flexx的指南