【问题标题】:image auto stretches in flexboxflexbox中的图像自动拉伸
【发布时间】:2018-03-12 03:44:23
【问题描述】:

我想知道为什么我在这个带有 display flex 的 div 容器中放置的任何图像都会自动拉伸?如果我要为它设置一个宽度,我不能用justify-content 将它居中。

#container {
  display: flex;
  justify-content: center;
}

#container div {
  padding: 25px;
  background: blue;
  color: white;
  width: 500px;
  display: flex;
  flex-direction: column;
}

#container div h1 {
  display: flex;
  justify-content: center;
}

#container input,
#container button {
  width: 75%;
}

#container img {
  display: flex;
  justify-content: center;
}
<div id="container">
  <div>
    <h1>a</h1>
    <img src="https://placehold.it/350x150">
    <input type="text" name="a">
    <input type="text" name="b">
    <button>a</button>
  </div>
</div>

https://jsfiddle.net/nqt8bw4z/ 自动拉伸 https://jsfiddle.net/nqt8bw4z/2/ 固定宽度但不居中

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    弹性容器的初始设置是align-items: stretch。这意味着弹性项目将扩展容器cross axis 的全长。这将是flex-direction: row 中容器的高度和flex-direction: column 中的宽度。

    由于您使用的是列方向 flex 容器,因此默认情况下图像会水平拉伸。您可以使用另一个值覆盖此设置。试试align-items: flex-startcenter

    #container {
      display: flex;
      justify-content: center;
    }
    
    #container div {
      display: flex;
      flex-direction: column;
      align-items: center;  /* NEW */
      width: 500px;
      padding: 25px;
      background: blue;
      color: white;
    }
    
    #container div h1 {
      display: flex;
      justify-content: center;
    }
    
    #container input,
    #container button {
      width: 75%;
    }
    
    #container img {
      display: flex;
      justify-content: center;
    }
    <div id="container">
      <div>
        <h1>
          a
        </h1>
        <img src="http://placehold.it/350x150" />
        <input type="text" name="a" />
        <input type="text" name="b" />
        <button>
          a
        </button>
      </div>
    </div>

    【讨论】:

    • 重要的是他不能通过在图像本身上使用justify-content: center;来对齐它[他也不能使它成为一个弹性容器]
    【解决方案2】:

    除了@Michael_B 的答案之外,您的代码还可以像下面这样简化,因为您不需要所有这些 flexbox 属性。

    #container div {
      padding: 25px;
      background: blue;
      color: white;
      width: 500px;
      margin:auto;
      display: flex;
      flex-direction: column;
      align-items:center;
    }
    
    #container input,
    #container button {
      width: 75%;
    }
    <div id="container">
      <div>
        <h1>a</h1>
        <img src="https://placehold.it/350x150">
        <input type="text" name="a">
        <input type="text" name="b">
        <button>a</button>
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 2019-12-22
      • 2017-02-25
      • 2017-06-17
      • 2016-05-04
      • 2022-11-01
      • 2016-08-17
      • 2018-01-26
      • 2017-03-20
      • 2012-07-25
      相关资源
      最近更新 更多