使用flexbox布局如何水平拉伸元素?

8

我正在尝试将内部对象水平拉伸,以便它们填满其容器的宽度。

这是我的代码:

<!DOCTYPE html>
<html>
<head>
<style>
.flex-container {
  display: flex;
  height: 200px;
  align-items: stretch;
  background-color: DodgerBlue;
}

.flex-container > div {
  background-color: #f1f1f1;
  margin: 10px;
  text-align: center;
  line-height: 75px;
  font-size: 30px;
}
</style>
</head>
<body>
<h1>The align-items Property</h1>

<p>The "align-items: stretch;" stretches the flex items to fill the container (this is default):</p>

<div class="flex-container">
  <div>1</div>
  <div>2</div>
  <div>3</div>  
</div>

</body>
</html>
内部元素高度通过属性进行了拉伸:
align-items: stretch;

如何拉伸这些元素的宽度呢?
2个回答

15
只需将 flex:1 添加到 flex 项:

.flex-container {
  display: flex;
  height: 200px;
  align-items: stretch;
  background-color: DodgerBlue;
}

.flex-container > div {
  background-color: #f1f1f1;
  margin: 10px;
  text-align: center;
  line-height: 75px;
  font-size: 30px;
  flex: 1;
}
<h1>The align-items Property</h1>

<p>The "align-items: stretch;" stretches the flex items to fill the container (this is default):</p>

<div class="flex-container">
  <div>1</div>
  <div>2</div>
  <div>3</div>  
</div>

这个指南可能非常有帮助:https://css-tricks.com/snippets/css/a-guide-to-flexbox/


2
您正在使用默认的flex-direction: row来使用 flexbox。它会将元素放在一行并根据它们的初始宽度和 flex 属性调整宽度。
这意味着align-items: stretch; 会拉伸这些元素,使它们适应父元素的高度而不是宽度,因为它们的宽度由 flex 属性定义。
使用flex: 1 1 auto; 使元素适应其父元素。
请参见https://css-tricks.com/snippets/css/a-guide-to-flexbox/ 了解更多详情。

我不希望“此项应水平拉伸”成为一个弹性项的属性。相反,我希望“此行弹性盒子应水平拉伸其项,除非每个项被覆盖”成为整个弹性盒子的属性。如何实现? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接