Ensure the content of a textarea input is consistently centered vertically

I am currently working on a small project that involves using textareas. One issue I have encountered is that the text always starts at the top-left corner of the textarea.

What I would like to achieve is having the content inside the textarea always centered. I envision that when I add a new line, the text expands from the center, similar to the following illustrations:

https://i.sstatic.net/SWMmY.png https://i.sstatic.net/6NL8O.png

I have explored options like vertical alignment and inserting a div, but I am curious if there is a solution that can be achieved using just the textarea element itself.

Thank you!

Answer №1

It may not be possible to vertically align text in a textarea, but there is a workaround!

Here is how you can achieve it using HTML and CSS:

  1. Start by creating a resizable div
  2. Add a contenteditable p within the div
  3. Include a placeholder for the p when it is empty
  4. Utilize flexbox to vertically align the p: align-items: center;
  5. Prevent overflow by adding p {white-space: pre-line;}
  6. Remove the border on focus with
    p {outline: 0px solid transparent;}

For the JavaScript part:

  1. Retrieve the target element (p)
  2. Set up an event listener for keypress
  3. Detect the 'Enter' key press
  4. Replace the default behavior with inserting a line break (new line)
  5. Add an event listener for click on the div to focus on the p (mimicking textarea behavior)

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

// Set up event listener for keypress
p.addEventListener('keypress', (e) => {
  let keyCode = e.code || e.key;
  // Detect 'Enter' key press
  if(keyCode === 'Enter') {
    // Replace default behavior with inserting line break
    document.execCommand('insertLineBreak');
    e.preventDefault();
  }
});

// Set up event listener for click
div.addEventListener('click', () => {
  // Focus on p to mimic 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

unable to connect to the web service using webview

When attempting to call a web service or display an alert, I am encountering some issues: Here is the code from my activity: mWebView = (WebView)findViewById(R.id.webViewRootAciviy); mWebView.setWebViewClient(new WebViewClient()); mWebView.setWebChromeCl ...

Encountered a problem with AngularUniversal prerendering: UnhandledPromiseRejectionWarning: Unable to locate NgModule metadata for 'class{}'

Objective The task may seem lengthy, but it's straightforward! Currently, I am utilizing Angular Universal for Server-Side Rendering (SSR) by following a tutorial. The Universal/express-engine has been installed, main.js is generated in the dist/pro ...

Utilizing jQuery to Capture Select Change Events

I am trying to automatically select a hidden option based on the value selected in a visible select. Here is my jQuery code: $(document).ready(function() { var selected_val = $('#id_foo option:selected').val(); $('#id_bar').va ...

Express.js response.json method can be used to render both HTML and JSON content in the

I have a router that is sending JSON data to the client as shown below: router.get('/', function(req, res, next) { UserModel.selectAllUsers(function(err, vals){ if(err){ console.log(err); } res.json({d: v ...

Steps for refreshing a React component following a data fetch operation

Currently, I am in the process of learning how to use React for building web applications. I have a basic React app that demonstrates the following features: Fetching a list of users Displaying the names of the users on individual cards once they are fetc ...

Failed to retrieve values from array following the addition of a new element

Does anyone have a solution for this problem? I recently added an element to my array using the push function, but when I tried to access the element at position 3, it wasn't defined properly processInput(inputValue: any): void { this.numOfIma ...

Having trouble with webpack displaying CSS background images?

I've set up the html boilerplate using webpack. I'm currently encountering an issue where calling an image in my scss file like "background: url('/img/img.png');" isn't working. I've included the webpack file and folder struct ...

Retrieve information stored in a component's data variable

After creating a Vue repository using vue init webpack my-app My main.js file looks like this -- // The Vue build version to load with the import command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue fro ...

Issue with Bootstrap 5 Navbar menu link functionality after implementing 'data-bs-toggle' and 'data-bs-target' properties

I found a solution to the issue with the responsive menu not working as expected after following a post: Bootstrap close responsive menu "on click" When I click on the menu link, it fails to move to the intended section on the page. <link rel="styl ...

Encountering an issue with React where the useContext hook is returning undefined instead of

I am facing an issue where I am attempting to access state and setState from the Store file, but it returns as undefined. Can someone help me understand what is causing this problem and how I can resolve it? import React, {createContext, useState} from &ap ...

Ways to determine the number of overlapping elements and adjust their widths

My layout conundrum involves 3 buttons within a flexbox placed in a single table cell. I am trying to adjust the width of each button so that they collectively fill the horizontal space as much as possible. The issue arises when the buttons overlap and the ...

Insert a new row into the table with a value that is taken from the input fields on the form

view image details I am working on a form that consists of 4 fields: Name, Last name, email, and role. There is also a button. When the button is clicked, the input from the above form should be added as a new row in a table below. ...

Vue transition not functioning properly when hovering over text for changes

When you hover over the circular region on the website, the text and description in the red box will change. To add a fade animation effect when the text changes, I attempted to use <transition> as per the documentation provided in this link. Unfor ...

NextJS 13 causes tailwind to malfunction when route group is utilized

I've encountered an issue in my NextJS 13 application where Tailwind classes are no longer being applied after moving page.tsx/layout.tsx from the root directory to a (main) directory within the root. I suspect that there may be a configuration that i ...

Error: Cannot access 'muiName' property as it is undefined

i am trying to display the elements of an array within a custom card component in a grid layout. However, when the page loads it freezes and the console shows "Uncaught TypeError: Cannot read property 'muiName' of undefined" custom car ...

Guide on downloading a file from Firebase storage within a Vue-based web application

Scenario: You are in a situation where you need to download a PDF file (or any file type) from Firebase storage to your computer using a browser that has a Vue.js web app with Vuetify components. Despite having looked at the Firebase storage documentatio ...

The issue of numbers not being properly summed in Node.js

I'm currently working on storing product prices in sessions. The issue arises when a product is clicked twice - instead of adding the two prices together, they concatenate into a single value. For example, 15 + 15 results in 01515. I'm unsure why ...

Regular expression that prohibits the acceptance of numbers with leading zeros

Below is the directive I am using to ensure that the input consists purely of numbers from 0-9. import { Directive, HostListener, ElementRef } from "@angular/core"; @Directive({ selector: "[numbersOnly]", }) export class OnlynumberDi ...

How to Incorporate an Anchor Link into a Div as well as its Pseudo Element using CSS, Javascript, or jQuery

How can I make both the menu item and its icon clickable as a link? When either is clicked, the link should work. Here is a CodePen example: http://codepen.io/emilychews/pen/wJrqaR The red square serves as the container for the icon that will be used. ...

Arrange Drifting Components in a Fluid Layout Grid

I am in the process of creating a unique sticky note website where I want to arrange the notes in a grid format. As the window size decreases, the notes should automatically reorganize to fit the width and allow for vertical scrolling. My goal is to achiev ...