mango mango - 1 year ago 102
CSS Question

Is there a way to animate the transition from text-align left to center in an input box



<input id = 'box' value = 'some text'/>


#box {


$('#box').on('click', function() {
$(this).css({'textAlign':'center'}, 500);

Right now the text just snaps to the center on click. I tried .animate() but nothing happened. Is there a way to animate a smooth transition from text-align left to center without snapping?

Answer Source

The only real way to achieve this is through some funky behind-the-scenes magic, using a temporary element that mimics the text inside the input.

Here's a working example:

$('#box').on('focus', function () {
    var full_width = $(this).width();
    var t = document.createElement('span');
    t.innerHTML = $(this).val(); = 'hidden';
    var text_width = $(t).width();
        'text-indent': (full_width - text_width) / 2

Keep in mind you'll have to style the temporary element's font-size, font-face and letter-spacing to be identical to the input box, otherwise it won't animate to the exact center.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download