Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically align text in textarea

Tags:

jquery

css

I am trying to find a solution to have the text typed in a textarea centered horizontally and vertically. Horizontally works fine with text-align: center; but centering vertically is much more of a hassle. It seems that the solution is using padding, but when the text is 3 lines high for example, the text is not centered anymore. In my fiddle below, I have placed a red line which is the center of my textarea. I would need this to be the center of where text will appear. Even if it is 1,2,3,4 or five lines high. So if I have 4 lines of text, the red line would need to be in between lines 2 and 3.

I am wondering if there might not be a work around this with jquery?

JS FIDDLE EXAMPLE

like image 265
Adrien Boufflet Avatar asked Apr 07 '15 19:04

Adrien Boufflet


People also ask

How do I center text vertically in textarea?

How do I align text in the middle of textarea? The answer was adding HTML5's contenteditable="true" on a table cell with style="vertical-align: middle".

How do you vertically align text?

Center the text vertically between the top and bottom margins. Select the text that you want to center. in the Page Setup group, and then click the Layout tab. In the Vertical alignment box, click Center.

How do you center a placeholder text vertically in textarea?

Use the line-height property to make the placeholder vertically centered.


1 Answers

I've come up with what I think is a very simple solution, which modifies the top padding as you type.

padding-top should always equal height/2 - font-size. Also, use box-sizing: border-box; to avoid problems with the default styling that's applied to textarea elements.

jQuery

$('.mytext').on('input', function() {
  var h= this.offsetHeight;
  $(this).css({   //clear current padding and height so we can use scrollHeight below
    paddingTop: 0,
    height: 0
  });

  $(this).css({
    paddingTop: Math.max(0, h/2 - this.scrollHeight/2),
    height: h
  });
});

$('.mytext')
  .on('input', function() {
    var h = this.offsetHeight;
    $(this).css({
      paddingTop: 0,
      height: 0
    });

    $(this).css({
      paddingTop: Math.max(0, h / 2 - this.scrollHeight / 2),
      height: h
    });
  })
  .trigger('input')
  .focus();
.mytext {
  resize: none;
  width: 280px;
  height: 150px;
  font-size: 20px;
  text-align: center;
  box-sizing: border-box;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="mytext" placeholder="type text here"></textarea>
like image 97
Rick Hitchcock Avatar answered Nov 15 '22 03:11

Rick Hitchcock