Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS all initial breaks firefox newline in textareas

Newline in textareas doesn't work in firefox when all: initial is set ...

https://jsfiddle.net/2bhzxdmg/

A idea how to resolve this (And I mean not be don't using the all: initial ... that is obvious)?

textarea {
  all: initial;
  background: #fff;
  padding: 10px;
  border: solid 1px #ddd;
}
<textarea></textarea>
like image 434
GDY Avatar asked Dec 07 '16 06:12

GDY


People also ask

How do I preserve line breaks when getting text from a textarea?

To preserve line breaks when getting text from a textarea with JavaScript, we can replace whitespace characters with '<br>\n' . const post = document. createElement("p"); post. textContent = postText; post.

How do you preserve a new line in HTML?

The <pre> tag defines preformatted text. Text in a <pre> element is displayed in a fixed-width font, and the text preserves both spaces and line breaks. The text will be displayed exactly as written in the HTML source code.

How do you stop a line break in HTML?

There are several ways to prevent line breaks in content. Using &nbsp; is one way, and works fine between words, but using it between an empty element and some text does not have a well-defined effect. The same would apply to the more logical and more accessible approach where you use an image for an icon.


2 Answers

You can solve it by adding white-space: pre-wrap:

Whitespace is preserved by the browser. Text will wrap when necessary, and on line breaks. (Source: W3schools)

The white-space is not preserved in Firefox because of the difference in initial user agent styles for textarea.

See demo below:

document.getElementById('sub').addEventListener('click', function() {
  console.log(document.getElementById('text').value);
})
textarea {
  all: initial;
  white-space: pre-wrap;
  background: #fff;
  padding: 10px;
  border: solid 1px #ddd;
}
<textarea id="text"></textarea>
<button id="sub">Get</button>
like image 109
kukkuz Avatar answered Nov 10 '22 08:11

kukkuz


Use the browser's inspect tools to see what the default styles are without all:initial.
The default white-space property for a textarea turns out to be pre-wrap. So, that's the solution.

textarea {
  all: initial;
  background: #fff;
  padding: 10px;
  border: solid 1px #ddd;
  white-space: pre-wrap;  /* here you go. */
}
<textarea></textarea>
like image 23
Mr Lister Avatar answered Nov 10 '22 08:11

Mr Lister