166

I have ghost text in textfields that disappear when you focus on them using HTML5's placeholder attribute:

<input type="text" name="email" placeholder="Enter email"/>

I want to use that same mechanism to have multiline placeholder text in a textarea, maybe something like this:

<textarea name="story" placeholder="Enter story\n next line\n more"></textarea>

But those \ns show up in the text and don't cause newlines... Is there a way to have a multiline placeholder?

UPDATE: The only way I got this to work was utilizing the jQuery Watermark plugin, which accepts HTML in the placeholder text:

$('.textarea_class').watermark('Enter story<br/> * newline', {fallback: false});
4
  • IE seems to handle it properly. Firefox OTOH just ignores the newlines
    – ekkis
    Dec 10, 2013 at 2:26
  • 1
    stackoverflow.com/questions/7312623/… is a very similar question with good answers too. Apr 15, 2014 at 15:50
  • if you're encountering this and using js to set the value check css white-space to make sure it's set correctly e.g. pre-wrap May 4, 2020 at 22:03
  • From that other question: &#10; works everywhere except Safari.
    – Sphinxxx
    May 4, 2020 at 22:27

16 Answers 16

87

For <textarea>s the spec specifically outlines that carriage returns + line breaks in the placeholder attribute MUST be rendered as linebreaks by the browser.

User agents should present this hint to the user when the element's value is the empty string and the control is not focused (e.g. by displaying it inside a blank unfocused control). All U+000D CARRIAGE RETURN U+000A LINE FEED character pairs (CRLF) in the hint, as well as all other U+000D CARRIAGE RETURN (CR) and U+000A LINE FEED (LF) characters in the hint, must be treated as line breaks when rendering the hint.

Also reflected on MDN: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-placeholder

FWIW, when I try on Chrome 63.0.3239.132, it does indeed work as it says it should.

1
  • 37
    except that the title attribute does not behave the same way i.e. it does not show ghost content. in fact it would be perfectly appropriate for placeholders to support multiple lines for text areas since text areas are multi-line creatures. pity the spec doesn't allow it. I guess the hacks will have to do. sigh
    – ekkis
    Dec 10, 2013 at 2:25
77

On most (see details below) browsers, editing the placeholder in javascript allows multiline placeholder. As it has been said, it's not compliant with the specification and you shouldn't expect it to work in the future (edit: it does work).

This example replaces all multiline textarea's placeholder.

var textAreas = document.getElementsByTagName('textarea');

Array.prototype.forEach.call(textAreas, function(elem) {
    elem.placeholder = elem.placeholder.replace(/\\n/g, '\n');
});
<textarea class="textAreaMultiline" 
          placeholder="Hello, \nThis is multiline example \n\nHave Fun"
          rows="5" cols="35"></textarea>

JsFiddle snippet.

Expected result

Expected result


Based on comments it seems some browser accepts this hack and others don't.
This is the results of tests I ran (with browsertshots and browserstack)

  • Chrome: >= 35.0.1916.69
  • Firefox: >= 35.0 (results varies on platform)
  • IE: >= 10
  • KHTML based browsers: 4.8
  • Safari: No (tested = Safari 8.0.6 Mac OS X 10.8)
  • Opera: No (tested <= 15.0.1147.72)

Fused with theses statistics, this means that it works on about 88.7% of currently (Oct 2015) used browsers.

Update: Today, it works on at least 94.4% of currently (July 2018) used browsers.

13
  • 1
    That jsfiddle example doesn't work at all... It's only multilined because the size of the textarea.
    – sebnukem
    Oct 21, 2014 at 17:30
  • 3
    There's a typo, but I can't edit because StackOverflow give me this "Edits must be at least 6 characters" error. Your class should be multiline not multiligne Feb 14, 2015 at 4:05
  • @sebnukem: It works on most browsers that i had test out. And it's not a matter of textarea's size. Can you provide more information on the issue you had ?
    – Cyrbil
    May 9, 2015 at 15:40
  • Doesn't work on safari it seems... - the \n disappears but everything is on a single line
    – Hackeron
    Jun 21, 2015 at 12:20
  • 1
    @Jroonk: I can confirm that. It's not due to chrome but to Apple forcing any browser to uses its IOS's WKWebView. Subsequently, any browser on IOS won't render this hack properly until WKWebView does.
    – Cyrbil
    Oct 25, 2018 at 9:26
61

I find that if you use a lot of spaces, the browser will wrap it properly. Don't worry about using an exact number of spaces, just throw a lot in there, and the browser should properly wrap to the first non space character on the next line.

<textarea name="address" placeholder="1313 Mockingbird Ln         Saginaw, MI 45100"></textarea>
3
  • 2
    Yep multiline placeholders are not supported crossbrowser, have found the latest safari does support but is definitely not supported on IOS5
    – Tom
    Jan 23, 2013 at 14:57
  • 8
    that doesn't work for me in either IE nor Firefox Windows. it just inserts the spaces I asked for it to
    – ekkis
    Dec 10, 2013 at 2:29
  • Chrome 37 is displaying placeholder text in a textarea without stripping the newlines. Does anyone know what the name of the 'feature' is so that I can a) look for it, and b) test for it?
    – Ben
    Jul 2, 2014 at 6:35
23

There is actual a hack which makes it possible to add multiline placeholders in Webkit browsers, Chrome used to work but in more recent versions they removed it:


First add the first line of your placeholder to the html5 as usual

<textarea id="text1" placeholder="Line 1" rows="10"></textarea>

then add the rest of the line by css:

#text1::-webkit-input-placeholder::after {
    display:block;
    content:"Line 2\A Line 3";
}

If you want to keep your lines at one place you can try the following. The downside of this is that other browsers than chrome, safari, webkit-etc. don't even show the first line:

<textarea id="text2" placeholder="." rows="10"></textarea>​

then add the rest of the line by css:

#text2::-webkit-input-placeholder{
    color:transparent;
}

#text2::-webkit-input-placeholder::before {
    color:#666;
    content:"Line 1\A Line 2\A Line 3\A";
}

Demo Fiddle

It would be very great, if s.o. could get a similar demo working on Firefox.

2
  • thanks for providing the fiddle link. it makes it easy to verify behaviour in various browsers. on IE 10 both versions fail, as well as on FF 12 (Windows). pity that. Safari 6.1 works :(
    – ekkis
    Dec 10, 2013 at 2:59
  • 1
    No longer works in Chrome - for a long time now, I'd assume. Feb 22, 2017 at 14:08
22

According to MDN,

Carriage returns or line-feeds within the placeholder text must be treated as line breaks when rendering the hint.

This means that if you just jump to a new line, it should be rendered correctly. I.e.

<textarea placeholder="The car horn plays La Cucaracha.
You can choose your own color as long as it's black.
The GPS has the voice of Darth Vader.
"></textarea> 

should render like this:

enter image description here

2
  • 1
    Works in the latest Chrome.
    – Avatar
    Jul 16, 2021 at 5:44
  • This method is the easiest to implement. It honors tabs too.
    – Dan Swain
    Aug 23, 2022 at 23:30
9

If you're using AngularJS, you can simply use braces to place whatever you'd like in it: Here's a fiddle.

<textarea rows="6" cols="45" placeholder="{{'Address Line1\nAddress Line2\nCity State, Zip\nCountry'}}"></textarea>
1
  • 4
    I am using similar approach but it is not working in Safari and Firefox
    – stan
    Aug 15, 2017 at 16:18
9

React:

If you are using React, you can do it as follows:

placeholder={'Address Line1\nAddress Line2\nCity State, Zip\nCountry'}
1
  • I couldn't get this working in React 18. Not sure why.
    – RyanNerd
    Jul 20, 2022 at 9:43
8

This can apparently be done by just typing normally,

<textarea name="" id="" placeholder="Hello awesome world. I will break line now

Yup! Line break seems to work."></textarea>

0
3

The html5 spec expressly rejects new lines in the place holder field. Versions of Webkit /will/ insert new lines when presented with line feeds in the placeholder, however this is incorrect behaviour and should not be relied upon.

I guess paragraphs aren't brief enough for w3 ;)

3
  • 1
    Webkit's behavior is not incorrect since the specification does not say what must happen if CR/LF do exist.
    – Christian
    Dec 16, 2011 at 11:26
  • 1
    @Christian It does now, it says "User agents should present this hint to the user, after having stripped line breaks from it...". It says this about stripping line breaks: "When a user agent is to strip line breaks from a string, the user agent must remove any "LF" (U+000A) and "CR" (U+000D) characters from that string.". May 28, 2014 at 10:51
  • This answer is no longer true. The spec now expressly requires that linebreaks in the placeholder be rendered as linebreaks.
    – Clonkex
    Aug 13, 2019 at 3:34
2

If your textarea have a static width you can use combination of non-breaking space and automatic textarea wrapping. Just replace spaces to nbsp for every line and make sure that two neighbour lines can't fit into one. In practice line length > cols/2.

This isn't the best way, but could be the only cross-browser solution.

<textarea class="textAreaMultiligne" 
          placeholder="Hello,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; This&nbsp;is&nbsp;multiligne&nbsp;example Have&nbsp;Fun&nbsp;&nbsp;&nbsp;&nbsp;"
          rows="5" cols="35"></textarea>

2

With Vue.js:

<textarea name="story" :placeholder="'Enter story\n next line\n more'"></textarea>
1
  • another way :placeholder="`/robots.txt \r\n /google-analytics-auth.html`"
    – Kingsley
    Jan 20, 2021 at 16:24
2

in php with function chr(13) :

echo '<textarea class="form-control" rows="5" style="width:100%;" name="responsable" placeholder="NOM prénom du responsable légal'.chr(13).'Adresse'.chr(13).'CP VILLE'.chr(13).'Téléphone'.chr(13).'Adresse de messagerie" id="responsable"></textarea>';

The ASCII character code 13 chr(13) is called a Carriage Return or CR

1
  • This worked for me but can you please explain the logic or theory behind it? Dec 17, 2020 at 12:41
1

You can try using CSS, it works for me. The attribute placeholder=" " is required here.

<textarea id="myID" placeholder=" "></textarea>
<style>
#myID::-webkit-input-placeholder::before {
    content: "1st line...\A2nd line...\A3rd line...";
}
</style>
0

Bootstrap + contenteditable + multiline placeholder

Demo: https://jsfiddle.net/39mptojs/4/

based on the @cyrbil and @daniel answer

Using Bootstrap, jQuery and https://github.com/gr2m/bootstrap-expandable-input to enable placeholder in contenteditable.

Using "placeholder replace" javascript and adding "white-space: pre" to css, multiline placeholder is shown.

Html:

<div class="form-group">
    <label for="exampleContenteditable">Example contenteditable</label>
    <div id="exampleContenteditable" contenteditable="true" placeholder="test\nmultiple line\nhere\n\nTested on Windows in Chrome 41, Firefox 36, IE 11, Safari 5.1.7 ...\nCredits StackOveflow: .placeholder.replace() trick, white-space:pre" class="form-control">
    </div>
</div>

Javascript:

$(document).ready(function() {
    $('div[contenteditable="true"]').each(function() {
        var s=$(this).attr('placeholder');
        if (s) {
            var s1=s.replace(/\\n/g, String.fromCharCode(10));
            $(this).attr('placeholder',s1);
        }
    });
});

Css:

.form-control[contenteditable="true"] {
    border:1px solid rgb(238, 238, 238);
    padding:3px 3px 3px 3px;
    white-space: pre !important;
    height:auto !important;
    min-height:38px;
}
.form-control[contenteditable="true"]:focus {
    border-color:#66afe9;
}
0

If you're using a framework like Aurelia that allows one to bind view-model properties to HTML5 element properties, then you can do the following:

<textarea placeholder.bind="placeholder"></textarea>
export class MyClass {
  placeholder = 'This is a \r\n multiline placeholder.'
}

In this case the carriage return and line feed is respected when bound to the element.

-1

Watermark solution in the original post works great. Thanks for it. In case anyone needs it, here is an angular directive for it.

(function () {
  'use strict';

  angular.module('app')
    .directive('placeholder', function () {
      return {
        restrict: 'A',
        link:     function (scope, element, attributes) {
          if (element.prop('nodeName') === 'TEXTAREA') {
            var placeholderText = attributes.placeholder.trim();

            if (placeholderText.length) {
              // support for both '\n' symbol and an actual newline in the placeholder element
              var placeholderLines = Array.prototype.concat
                .apply([], placeholderText.split('\n').map(line => line.split('\\n')))
                .map(line => line.trim());

              if (placeholderLines.length > 1) {
                element.watermark(placeholderLines.join('<br>\n'));
              }
            }
          }
        }
      };
    });
}());

Not the answer you're looking for? Browse other questions tagged or ask your own question.