0

I'm wondering why any image I put in this div container with display flex is automatically stretched out? And if I were to set a width for it, I can't center it with 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/ auto stretch https://jsfiddle.net/nqt8bw4z/2/ fixed width but doesn't center

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
totalnoob
  • 2,521
  • 8
  • 35
  • 69

2 Answers2

1

An initial setting of a flex container is align-items: stretch. This means that flex items will expand the full length of the container's cross axis. That would be the container's height in flex-direction: row, and width in flex-direction: column.

Since you're working with a column-direction flex container, the image is stretching horizontally by default. You can override this setting with another value. Try align-items: flex-start or center.

#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;
}
<div id="container">
  <div>
    <h1>
      a
    </h1>
    <img src="http://placehold.it/350x150" />
    <input type="text" name="a" />
    <input type="text" name="b" />
    <button>
      a
    </button>
  </div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • 1
    and the important part is that he cannot align it by using `justify-content: center;` on the image itself [also he cannot make it a flex container] – Temani Afif Mar 11 '18 at 19:40
0

In addition to the answer of @Michael_B your code can be simplifed like below as you don't need all these flexbox properties.

#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%;
}
<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>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415