简体   繁体   中英

centering text inside a textarea while changing the font size

I want to fix the text inside the textarea when I dynamically change the font size (I want to center the text inside the textrea vertically and horizontally). so I set the display: table-cell; vertical-align: middle; display: table-cell; vertical-align: middle; but still when change the font size the text position changes.

in lower sizes the text gos up and in huge font sizes the text goes down.

How can I do this?

Here is a prototype:

 setTimeout(() => { const textarea = document.getElementsByTagName("textarea")[0]; textarea.style.overflow = "hidden"; textarea.style.userSelect = 'none'; $('textarea').val("I should be centered"); $('textarea').css('font-size', 12); }, 2000); setTimeout(() => { $('textarea').val("I should be centered"); $('textarea').css('font-size', 52); }, 4000); setTimeout(() => { $('textarea').val("I should be centered"); $('textarea').css('font-size', 100); }, 6000);
 <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> <textarea style="font-family: &quot;Open Sans Semibold bold27772842&quot;, sans-serif; font-size: 53.9269px; line-height: normal; font-weight: normal; direction: ltr; text-align: center; color: rgb(230, 224, 236); padding: 5.6373px 9.3955px 0px; height: 81.4775px; transform: translate(0px, 7.02549px); display: table-cell; vertical-align: middle;"></textarea>

Have you tried using a div with contentEditable instead of a textarea ?

For instance:

 .textarea { position: relative; display: flex; align-items: center; justify-content: center; max-width: 500px; width: 100%; height: 200px; border: 1px solid gray; } .textarea-text { max-width: 90%; margin: 0 auto; text-align: center; } //meaningless styles .body { margin: 0 auto; display: block; max-width: 800px; width: 100%; margin: 20px; } .textarea-text, .textarea-text:focus, .textarea-text:hover { outline: unset; }
 <div class="body"> <div class="textarea"> <div class="textarea-text" contentEditable="true"> hello I'm an editable content. </div> </div> </div>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM