Run
Run

Reputation: 57176

CSS3 flex - stretches the image instead of centering it?

Why does flex center stretch my image instead of centering it?

css:

.flex-centre {
      display: flex;
      justify-content: center;
      flex-direction: column;
      text-align: center;
      height: 100%;
      width: 100%;
}

HTML:

<div style="height: 400px; width: 400px; background: #ccc">
    <div class="flex-centre">
        <img class="img-responsive" src="http://placekitten.com/g/200/200" alt="">
    </div>
</div>

Result:

enter image description here

Any ideas?

jsfiddle

Upvotes: 3

Views: 643

Answers (1)

Nenad Vracar
Nenad Vracar

Reputation: 122027

You have set flex-direction: column and now main axis is Y and cross axis is X. So because align-items distribute items along cross-axis (and default value of align-items is stretch) now you want to use align-items: center to position your image horizontally and prevent image to stretch.

.flex-centre {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  text-align: center;
  height: 100%;
  width: 100%;
}
<div style="height: 400px; width: 400px; background: #ccc">
  <div class="flex-centre">
    <img class="img-responsive" src="http://placekitten.com/g/200/200" alt="">
  </div>
</div>

Another option is to set left and right margin of image to auto

.flex-centre {
  display: flex;
  justify-content: center;
  flex-direction: column;
  text-align: center;
  height: 100%;
  width: 100%;
}
img {
  margin: 0 auto;
}
<div style="height: 400px; width: 400px; background: #ccc">
  <div class="flex-centre">
    <img class="img-responsive" src="http://placekitten.com/g/200/200" alt="">
  </div>
</div>

Upvotes: 6

Related Questions