'Align text on top of image using flex
.container{
display: flex;
align-items: center;
justify-content: center;
position:relative;
}
.text{
position:absolute;
left:0;
}
<div class="container">
<img src="http://lorempixel.com/800/800/" />
<div class="text">
<p>
some text here to be vertical aligned on the left where the image starts;
</p>
</div>
</div>
I would want that text to be on top of the image, centered vertically, on the left. Is there any other solution except of using:
position:absolute;
left:0;
I feel that it should be possible doing it with some flex attributes.
Thanks!
Solution 1:[1]
.container {
position: relative;
}
.text {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
align-items: center;
}
<div class="container">
<img src="http://lorempixel.com/800/800/" />
<div class="text">
<p>
some text here to be vertical aligned on the left where the image starts;
</p>
</div>
</div>
What I did:
- Make a container the size of the image: simply put the
imgalone in a div - Make the above container a positioning context:
position: relative - Create a container for aligning stuff in it, the size of its positioning context:
position: absoluteand all edges on0 - Center vertically:
display: flexplusalign-items: center
Of course, there are other lots of ways to achieve the same effect (even completely avoiding position absolute), but I would recommend using positioning in this situation.
Solution 2:[2]
was struggling with this. Played with position with bad results until it hit me. Just flex-direction: column (or column-reverse if necessary)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alin Purcaru |
| Solution 2 | Ivan Dario Niello |
