RogerFedFan
RogerFedFan

Reputation: 566

Aligning Images with Flexbox

I'm trying to have 1 image on the top with 2 images below it spanning half the width of the image on top. The problem I'm encountering are aligning issues with the 2 images in which they don't fit nicely below the top image but spaced perfectly to the sides. I'm trying to have the 2 images be below the top image perfectly aligned in the center with no spaces below. As I shrink the window, that is when it looks like I want it to on a full screen except without the spaces. I also want them perfectly aligned in the center of the screen.

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>

Upvotes: 0

Views: 38

Answers (2)

jas7457
jas7457

Reputation: 1782

This might be a bit better, as it doesn't rely on setting pixel values for anything: 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;
}

Upvotes: 1

Gerard Reches
Gerard Reches

Reputation: 3154

Just remove margin:auto from the images and use justify-content: center in the flex containers.

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

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

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

.second img {
  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>

Upvotes: 1

Related Questions