首页 > 解决方案 > 使用 flex-box 时如何水平拉伸元素

问题描述

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

这是我的代码:

<!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>

由于该属性,内部 div 元素的高度被拉伸:

align-items: stretch;

如何也拉伸这些元素的宽度?

标签: csswebflexbox

解决方案


只需添加flex:1到弹性项目:

.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/


推荐阅读