Reputation: 15
How can I get text centered vertically on an image? I already made a setup on how it should look but I can't get the text to be centered on every image because they have different heights.
I have already tried using the "top" property and vertical-align and methods mentioned in other questions but nothing seems to work for this situation.
Is there anyway this can be achieved?
The JSfiddle can be found here: http://jsfiddle.net/Sf3RX/2/
HTML
<div class="column">
<div class="image">
<img src="/">
<p class="info">cats
<br><span>#Photography</span>
</p>
</div>
CSS
.image {
position: relative;
width: 25%;
text-align: center;
}
img {
width: 100%;
}
p.info {
position: absolute;
width: 100%;
z-index: 10;
top: 25%;
}
Upvotes: 0
Views: 593
Reputation:
<style>
body{
padding: 0;
margin: 0;
margin:0px auto;
}
#main{
position: relative;
width:500px;
height:500px;
}
#abc{
text-align:center;
background-color:#0F0;
height:250px;
display: table;
width: 100%;
}
#abc span {
vertical-align:middle;
display: table-cell;
}
</style>
<div id="main">
<div id="abc">
<span>asdfasdfafasdfasdf<br/> sdfjdsl flkjdsflk sjdflkjdsf </span>
</div>
</div>
Upvotes: 0
Reputation: 9530
If you want to achieve this result http://jsfiddle.net/paulalexandru/MSfPs/ all you have to do is to :
Adjust your css like this:
p.info {
position: absolute;
width: 100%;
z-index: 10;
top: 25%;
margin: 0;
padding: 0;
}
And add this javascript code also:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$(".image").each(function() {
var height_image = $(this).find('img').height();
var height_p = $(this).find('p.info').height();
var rest = height_image - height_p;
$(this).find('p.info').css('top', rest/2);
});
});
</script>
The javascript code calculates the css top property for every <p>
in order for them to be in the middle of the block.
Another pure css solution is to change your html code a little bit, you have to add a table height 100% / width 100% and set a vertical-align: middle on the <td>
and inside it you should put the paragraph.
Upvotes: 1
Reputation: 1308
You can set line-height
to 100%, which will make the line the same height as your image, vertically centering it.
Upvotes: 0
Reputation:
Try line-height
, or top:50%;margin-top://-the height of the Textblock
Upvotes: 0