Reputation: 921
I am trying to get text absolutely centered inside an html div, even when it is wider than the enclosing div.
The text is center-aligned as long as it is smaller than the enclosing div, but when it exceeds the width of the enclosing width it gets left-justified (I checked this on recent versions of Chrome, FF, IE).
I have this:
<style>
.container {
position: relative;
width: 300px;
height: 200px;
text-align: center;
margin: auto;
white-space: nowrap;
overflow: hidden;
background: silver;
}
.line {
position: absolute;
width:100%;
font-size: 40px;
}
</style>
<div class="container">
<div class="line">
PLEASE ALIGN ME TO THE CENTER
</div>
</div>
See http://jsfiddle.net/acc4u/5/ for a live version of the code above - You can decrease the font size to see how this is is center-aligned when narrower.
I could use the left:-nnpx
css attribute and that would get the job done, but that would be extremely inflexible as I would need to calculate the text's width to compute the offset. Since I intend to animate the size of the text, this would need to be calculated dynamically.
Upvotes: 1
Views: 101
Reputation: 228162
Based on Aligning image to center inside a smaller div, I made this: http://jsfiddle.net/thirtydot/x62nV/2/.
It seems fine, except for that on WebKit browsers, when you move the mouse up and down, the text is very shaky.
Upvotes: 2