【问题标题】:How to horizontally stretch elements when using flex-box使用 flex-box 时如何水平拉伸元素
【发布时间】:2019-04-10 21:28:24
【问题描述】:

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

这是我的代码:

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

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

【问题讨论】:

    标签: css web flexbox


    【解决方案1】:

    只需将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/

    【讨论】:

      【解决方案2】:

      您正在使用默认为flex-direction: row 的弹性框。它将元素放在一行中,并根据它们的初始宽度和 flex 属性调整它们的宽度。

      这意味着align-items: stretch; 将以这种方式拉伸项目,使它们适合父元素,但不是宽度,而是高度。因为它们的宽度由 flex 属性定义;

      使用flex: 1 1 auto; 使元素适合它的父元素。

      请参阅https://css-tricks.com/snippets/css/a-guide-to-flexbox/ 了解更多详情。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-18
        • 2022-11-30
        • 2020-11-10
        • 1970-01-01
        • 2019-10-08
        相关资源
        最近更新 更多