html - 为什么 flex 元素不拉伸(stretch)对齐元素和对齐内容

标签 html css flexbox

第一次编辑:如果我使用 align-items: stretch; 我可以拉伸(stretch)我的 flex 元素,我不知道该怎么做,但是我在玩弄它,认为我也应该将此信息添加为编辑,align-items: stretch 值,拉伸(stretch) flex 元素。

第二次编辑: 好吧,可能我不清楚,我不是在寻找解决方案,我只是想知道为什么它不使用 justify-content 进行拉伸(stretch),就是这样,我可以解决这个问题我自己,通过编辑代码,但我想知道原因,为什么它会按照它的方式行事。

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

但我的问题是不同的,只要我添加 align-items,flex-items 就会停止拉伸(stretch),在添加这个属性之前它们工作正常,我知道我可以通过添加高度来解决这个问题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
}
<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>

最佳答案

您的 box 元素不能同时stretchcenter

结合 align-itemsalign-content 不会发生这种情况,因为 align-items 应用于单行的 flex 元素和 align-content 当它们换行时。

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


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

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


假设它是 box 中的 text 您想要居中,以及要拉伸(stretch)的 box ,只需将 box 也是一个 flex 容器。

添加显示: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
}
<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>

关于html - 为什么 flex 元素不拉伸(stretch)对齐元素和对齐内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45205514/

相关文章:

html - 如何创建 HTML/CSS 响应磁贴?

html - 居中动态div

css - float 可变高度容器

css - Chrome/Firefox 中不一致的 <img> 大小调整行为

css - IE11 中的 Flex 元素溢出容器

asp.net - 关于响应式网页设计的建议

html - CSS 清除 float 不起作用

html - 是否可以过滤具有特定类别的部分?

javascript - 如何动画 svg 路径填充 javascript 而不是 HTML

android - react native : Get flexDirection row items to render on next render if outside of view's boundaries