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?
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>
Have a look at this code snippet, it might solve your problem :
http://codepen.io/desandro/pen/gICqd
It relies on CSS and a wrapper div :
#wrap {
width: 50%;
position: relative;
font-family: sans-serif;
height: 70%;
border: 2px solid red;
}
#wrap .area {
resize: none;
outline: none;
border: 2px solid;
display: block;
width: 100%;
padding: 0;
position: absolute;
top: 0;
font-family: sans-serif;
font-size: 20px;
text-align: center;
}
#wrap textarea.area {
left: 0;
height: 100%;
border: 2px dotted blue;
background: transparent;
}
#wrap .dummy {
left: 100%;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.