Home > Software engineering >  Always vertically center content of a textarea input
Always vertically center content of a textarea input

Time:12-07

i'm working on a small project where textarea are used.

And the problem with textarea is that the text always start at the top left corner...

And what i want is to have the content inside of that textarea always centered. And then if I add a line it'll expend from the middle, something like this :

1 line 2 lines

I looked for thing like vertical align and thing like that, but i also saw things about inserting a div... But i was wondering if there was a solution with textarea

Thanks !

CodePudding user response:

I don't think you can align the text in textarea vertically, but you can fake it!

HTML and CSS:

  1. Create a resizable div
  2. Nest a contenteditable p in that div
  3. Add a placeholder for the p when it's empty
  4. Use flexbox to set the p in the middle: align-items: center;
  5. Add p {white-space: pre-line;} to prevent the overflow when typing
  6. Add p {outline: 0px solid transparent;} to remove the border on focus

JavaScript:

  1. Get the target (p)
  2. Add an event on keypress
  3. Check for pressing Enter
  4. Prevent the default event and insert a line break (new line) instead
  5. Add an event on click to the div to focus the p (textarea behavior)

// Get the target
let p = document.querySelector('p');
let div = document.querySelector('div');

// Add event onkeypress
p.addEventListener('keypress', (e) => {
  let keyCode = e.code || e.key;
  // Check for pressing 'Enter'
  if(keyCode === 'Enter') {
    // Prevent the default event and insert line break (new line) instead
    document.execCommand('insertLineBreak');
    e.preventDefault();
  }
});

// Add event onclick 
div.addEventListener('click', () => {
  // Focus on p to get the textarea behavior
  p.focus();
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

div {
    resize: both;
    width: 200px;
    height: 150px;
    border: 1px solid;
    overflow: auto;
    margin: 30px auto;
    display: flex;
    align-items: center;
    cursor: text;
}

p {
  white-space: pre-line;
  width: 100%;
  height: fit-content;
  outline: 0px solid transparent;
}

p:empty::before {
    content: attr(placeholder);
    color: #666666; 
}
<div>
  <p contenteditable="true" placeholder="Type here..."></p>
</div>

  • Related