图像自动伸展在flexbox中

时间:2018-03-11 19:30:33

标签: html css css3 flexbox

我想知道为什么我在这个带有显示器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/固定宽度但不居中

2 个答案:

答案 0 :(得分:1)

弹性容器的初始设置为align-items: stretch。这意味着弹性项目将扩展容器cross axis的全长。这将是data.iloc[45,25]=="DEC" 中容器的高度,flex-direction: row中的宽度。

由于您正在使用列方向灵活容器,因此默认情况下图像水平拉伸。您可以使用其他值覆盖此设置。试试flex-direction: columnalign-items: flex-start

&#13;
&#13;
center
&#13;
#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;
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

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

&#13;
&#13;
#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%;
}
&#13;
<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>
&#13;
&#13;
&#13;