Mark Boulder
Mark Boulder

Reputation: 14277

Flexbox horiz/vert centering goes outside of <img>

Trying to center Hello world horizontally/vertically inside .test while .test stretches to the size of .test img. What am I doing wrong?

http://jsfiddle.net/x06q69cc/

.test {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 5px solid blue;
}
.test img {
  width: 100%;
  display: block;
}
.test .test2 {
  max-width: 50%;
}
<div class="test">
  <img src="http://lorempixel.com/400/400">
  <div class="test2">
    <p>Hello world</p>
  </div>
</div>

Upvotes: 0

Views: 45

Answers (1)

phantomesse
phantomesse

Reputation: 251

Since you made .test a flexbox, the <img> and .test2 inside it will behave similarly in a flex child element fashion, which means that the <img> and .test2 will appear side by side.

One solution would be to make .test2 a flexbox instead of .test and have .test2 be absolutely positioned over .test.

.test {
    position: relative;
    border: 5px solid blue;
}

.test img {
    display: block;
    width: 100%;
}

.test .test2 {
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
}
<div class="test">
    <img src="http://lorempixel.com/400/400" />
    <div class="test2">
        <p>Hello world</p>
    </div>
</div>

Upvotes: 1

Related Questions