使用Flexbox对齐图像

时间:2017-04-28 15:49:47

标签: html css flexbox

我正在尝试在顶部放置1张图像,其下方有2张图像,横跨顶部图像宽度的一半。我遇到的问题是将问题与2张图像对齐,在这些图像中,它们不能很好地贴合在顶部图像下方,但与两侧完美间隔。我试图将2张图像放在顶部图像下方,在中心完全对齐,下面没有空格。当我缩小窗口时,就好像我想要它在全屏幕上,除了没有空格。我也希望它们在屏幕中央完美对齐。

https://jsfiddle.net/voryuja8/

.first {
  display: flex;
}

.first img {
  margin: auto;
  max-width: 800px;
}

.second {
  display: flex;
}

.second img {
  margin: auto;
  flex: 1;
  max-width: 400px;
}
<div class="first">
  <img src="https://sarahannephoto.files.wordpress.com/2015/01/devyn_015.jpg?w=1008" alt="">
</div>

<div class="second">
  <img src="http://preen.inquirer.net/files/2016/05/preen-emily-oberg-complex-e1463660455785.jpg" alt="">
  <img src="http://preen.inquirer.net/files/2016/05/preen-emily-oberg-complex-e1463660455785.jpg" alt="">
</div>

2 个答案:

答案 0 :(得分:1)

只需从图片中删除margin:auto,然后在弹性容器中使用justify-content: center

&#13;
&#13;
.first {
  display: flex;
  justify-content: center;
}

.first img {
  max-width: 800px;
}

.second {
  display: flex;
  justify-content: center;
}

.second img {
  flex: 1;
  max-width: 400px;
}
&#13;
<div class="first">
  <img src="https://sarahannephoto.files.wordpress.com/2015/01/devyn_015.jpg?w=1008" alt="">
</div>

<div class="second">
  <img src="http://preen.inquirer.net/files/2016/05/preen-emily-oberg-complex-e1463660455785.jpg" alt="">
  <img src="http://preen.inquirer.net/files/2016/05/preen-emily-oberg-complex-e1463660455785.jpg" alt="">
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这可能会更好一点,因为它不依赖于为任何事物设置像素值:https://jsfiddle.net/voryuja8/1/

HTML:     

<div class="second">
  <div class="flex-child">
     <img src="http://preen.inquirer.net/files/2016/05/preen-emily-oberg-complex-e1463660455785.jpg" alt="">
  </div>
  <div class="flex-child">
     <img src="http://preen.inquirer.net/files/2016/05/preen-emily-oberg-complex-e1463660455785.jpg" alt="">
  </div>
</div>

CSS:

img {
  max-width: 100%;
}

.second {
    display: flex;
}

.flex-child {
  flex-grow: 1;
  flex-shrink: 1;
}