I’m trying to vertically center text of an unknown height within a div of a known height. I’ve tried the css display: table-cell option, and it didn’t work so I’m using jQuery to detect the height and then apply a top margin, if necessary, in order to accomplish the centering – which works when something needs to be adjusted, but then doesn’t work to readjust it to have a top margin of zero.
This is my function:
function change_trend(){
trend_text = $('#trends_holder img:eq(' + item_count + ')').attr('data-content');
$('.trend_text').text(trend_text);
var trendMargin = $('.trends_scroller').height() - $('.trend_text').innerHeight();
$('.trend_text').css('marginTop',trendMargin);
}
The variable trendMargin is always either zero or twelve. If it’s zero, initially, everything is set properly. Then if it is twelve, it sets the top margin appropriately. But then when I get to the next item with a marginTop of zero, it doesn’t pop things back up into place where they were. How can I vertically align this stuff? It really doesn’t seem like vertical centering should be this hard…
This will do it:
HTML:
CSS:
To set the height of the DIV you use
line-heightinstead ofheight. Then, on the child (the container for the text), you setline-heightback to “normal”, and also setdisplay:inline-block(this is necessary).Live demo: http://jsfiddle.net/simevidas/5qXMj/1/