为什么 flex 项目没有通过对齐项目和对齐内容进行拉伸

use*_*957 0 html css flexbox

第一次编辑:如果我使用,align-items: stretch;我可以拉伸我的 flex 项目,我不知道该怎么做,但我在玩弄它,并认为我应该添加此信息作为编辑,align-items: stretch价值,拉伸弹性项目。

第二次编辑:好吧,可能我不清楚,我不是在寻找解决方案,我只是想知道为什么它没有用 justify-content 进行拉伸,就是这样,我可以通过编辑代码来解决这个问题,但是我想知道原因,为什么它的行为方式如此。

我已经阅读了这个答案Flex item not fill screen height with "align-items: stretch"

但我的问题是不同的,一旦我添加align-items,flex-items 停止拉伸,在添加这个属性之前它们工作正常,我知道我可以通过添加高度来解决这个问题100%,但我对此不感兴趣,我想知道为什么它会这样。 注意:我正在使用 chrome

我的代码请阅读代码中的注释

.container {
  font-size: 36px;
  height: 800px;
  border: 1px solid black;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  /* as soon as i add this align-items property or my items 
  stop streching, i don't get it, if use value stretch it streches 
  the my items, please read the note first edit in the question, 
  it is at the top */
  align-content: stretch;
}

.box {
  width: 400px;
  color: #fff;
}

.box1 {
  background: blue;
}

.box2 {
  background: red
}

.box3 {
  background: yellow
}

.box4 {
  background: black
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div class="box box1">Home</div>
  <div class="box box2">Menu</div>
  <div class="box box3">About Us</div>
  <div class="box box4">Contact Us</div>
</div>
Run Code Online (Sandbox Code Playgroud)

LGS*_*Son 7

你的box项目不能同时stretchcenter在同一时间。

组合align-items并且align-content不会像align-items应用于单行的 flex 项目以及align-content当它们换行时那样发生。

请注意,您不需要添加align-items/content并将它们的值设置为stretch,这是它们的默认值


至于解决方案,设置boxtoheight: 100%将使它们看起来被拉伸,但与使用align-items/content相比会给出完全不同的结果 stretch值。

固定高度时,它们将是设定的高度,无论是否有 2 行或更多行,stretch乳清都会调整它们的高度以适合它们的父级。简单地说,2 行会使它们高 50%,3 行会使它们高 33.33%,依此类推。


假设它是在文本box您想要为中心,与顺box向拉伸,简单地使box柔性容器了。

添加display: flex; align-items: centerbox,它可能会按照您想要的方式进行布局。

如果您希望文本也水平居中,我在这里添加了justify-content: center;,您可以保留或删除它。

.container {
  font-size: 36px;
  height: 800px;
  border: 1px solid black;
  display: flex;
  flex-wrap: wrap;
}

.box {
  width: 400px;
  color: #fff;
  display: flex;
  align-items: center;             /*  vertically center    */
  justify-content: center;         /*  horizontally center  */
}

.box1 {
  background: blue;
}

.box2 {
  background: red
}

.box3 {
  background: yellow
}

.box4 {
  background: black
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div class="box box1">Home</div>
  <div class="box box2">Menu</div>
  <div class="box box3">About Us</div>
  <div class="box box4">Contact Us</div>
</div>
Run Code Online (Sandbox Code Playgroud)