How can I vertically align a absolutely positioned p
element inside an image?
<div>
<img class="test-img" src="test.jpg">
<p class="tag">text with multiple lines here</p>
</div>
Since I don't know it's height.
EDIT
My image can't be a background, it's loaded in runtime. I want to place the text inside the image. What I have so far is like this image, my text is with top: 0
. I want now to vertically align it to be at the middle of the image.
My CSS:
.test-img {
height: 320px;
width: 240px;
}
.tag {
position: absolute;
top: 0;
}
div {
height: 320px;
width: 240px;
display: inline-block;
position: relative;
}
I don't know the height of my p
tag because it's text is taken from database.
There really isn't anything for CSS to do this (specifically because it has to be dynamic height) other than using display:table;
, but at least now days it has pretty good compatibility
.test-img {
height: 320px;
width: 240px;
display:block;
}
.inner {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: table;
}
.tag {
display: table-cell;
vertical-align: middle;
text-align: center;
font-size: 30px;
padding: 1em;
}
.outer {
height: 320px;
width: 240px;
position: relative;
}
<div class="outer">
<img class="test-img" src="//placehold.it/240x320">
<div class="inner">
<p class="tag">text with multiple lines here</p>
</div>
</div>