对齐周围空间相等的元素并保持纵横比?

时间:2017-12-22 07:20:22

标签: html css css3 flexbox

我试图证明3张图像的周围空间相等。我以百分比设置图像的宽度。我尝试使用flexbox和justify-content: space-evenly,但图片不保持宽高比:

Codepen



.container {
  width: 50%;
  border: 1px solid black;
  
  display: flex;
  justify-content: space-evenly;
}

.container img {
  width: 10%;
}

<div class="container">
  <img src="https://cdn2.iconfinder.com/data/icons/humano2/128x128/status/gtk-missing-image.png" />
  <img src="https://cdn2.iconfinder.com/data/icons/humano2/128x128/status/gtk-missing-image.png" />
  <img src="https://cdn2.iconfinder.com/data/icons/humano2/128x128/status/gtk-missing-image.png" />
</div>
&#13;
&#13;
&#13;

我需要保持宽高比

3 个答案:

答案 0 :(得分:1)

这将解决您的问题

我刚刚将align-items: center;添加到您的.container并解决了这个问题。

来自小提琴的工作样本:

.container {
  width: 50%;
  border: 1px solid black;
  display: flex;
  justify-content: space-evenly;
  align-items: center;
}

.container img {
  width: 10%;
}
<div class="container">
  <img src="https://cdn2.iconfinder.com/data/icons/humano2/128x128/status/gtk-missing-image.png" />
  <img src="https://cdn2.iconfinder.com/data/icons/humano2/128x128/status/gtk-missing-image.png" />
  <img src="https://cdn2.iconfinder.com/data/icons/humano2/128x128/status/gtk-missing-image.png" />
</div>

希望这对你有好处。

答案 1 :(得分:0)

试试这个justify-content: space-between; 如果这也不起作用,那么您可能没有使用chrome或最新版本的chrome。

答案 2 :(得分:0)

使用空的<span>space-between在每个<img>周围创建相等的空间。

试试这个:

&#13;
&#13;
.container {
  width: 50%;
  border: 1px solid black;
  
  display: flex;
  justify-content: space-between;
}

.container img {
  width: 10%;
}
&#13;
<div class="container">
<span></span>
<img src="https://cdn2.iconfinder.com/data/icons/humano2/128x128/status/gtk-missing-image.png" />
<img src="https://cdn2.iconfinder.com/data/icons/humano2/128x128/status/gtk-missing-image.png" />
<img src="https://cdn2.iconfinder.com/data/icons/humano2/128x128/status/gtk-missing-image.png" />
<span></span>
</div>
&#13;
&#13;
&#13;

或者更加优雅的方式,无需编辑HTML:

&#13;
&#13;
.container {
    width: 50%;
    border: 1px solid black;
  
    display: flex;
    justify-content: space-between;
}

.container::before, .container::after {
    content: "";
}

.container img {
    width: 10%;
}
&#13;
<div class="container">
<img src="https://cdn2.iconfinder.com/data/icons/humano2/128x128/status/gtk-missing-image.png" />
<img src="https://cdn2.iconfinder.com/data/icons/humano2/128x128/status/gtk-missing-image.png" />
<img src="https://cdn2.iconfinder.com/data/icons/humano2/128x128/status/gtk-missing-image.png" />
</div>
&#13;
&#13;
&#13;