Grow your CSS skills. Land your dream job.

Textarea Tricks

Published by Chris Coyier

Oh, <textarea>'s. How many quirks you posses. Here is a collection of nine things you might want to do related to textareas. Enjoy.

1. Image as textarea background, disappears when text is entered.

You can add a background-image to a textarea like you can any other element. In this case, the image is a friendly reminder to be nice =). If you add a background image, for whatever reason, it can break the browser default styling of the textarea. The default 1px solid bolder is replaced with a thicker beveled border. To restore the browser default, you can just force the border back to normal.

textarea {
  background: url(images/benice.png) center center no-repeat; /* This ruins default border */
  border: 1px solid #888; 
}

That background image might interfere with the readability of the text once the text reaches that far. Here is some jQuery that will remove the background when the textarea is in focus, and put it back if the textarea is left without any text inside.

$('textarea')
  .focus(function() { $(this).css("background", "none") })
  .blur(function() { if ($(this)[0].value == '') { $(this).css("background", "url(images/benice.png) center center no-repeat") } });

2. HTML5 placeholder text

There is a new attribute as part of HTML5 forms called placeholder. It shows faded gray text in the textarea (also works for text-style inputs) which disappears when the textarea is in focus or has any value.

<textarea placeholder="Remember, be nice!" cols="30" rows="5"></textarea>

HTML5 placeholder text works in Safari 5, Mobile Safari, Chrome 6, and the Firefox 4 alpha.

3. Placeholder text, HTML5 with jQuery fallback

We can easily test if a particular element supports a particular attribute by testing with JavaScript:

function elementSupportsAttribute(element, attribute) {
  var test = document.createElement(element);
  if (attribute in test) {
    return true;
  } else {
    return false;
  }
};

Then we can write code so that if the browser does support the placeholder attribute, we'll use that, if not, we'll mimic the behavior with jQuery:

if (!elementSupportsAttribute('textarea', 'placeholder')) {
  // Fallback for browsers that don't support HTML5 placeholder attribute
  $("#example-three")
    .data("originalText", $("#example-three").text())
    .css("color", "#999")
    .focus(function() {
        var $el = $(this);
        if (this.value == $el.data("originalText")) {
          this.value = "";
        }
    })
    .blur(function() {
      if (this.value == "") {
          this.value = $(this).data("originalText");
      }
    });
} else {
  // Browser does support HTML5 placeholder attribute, so use it.
  $("#example-three")
    .attr("placeholder", $("#example-three").text())
    .text("");
}

4. Remove the blue glow

All WebKit browsers, Firefox 3.6, and Opera 10 all put a glowing blue border around textareas when they are in focus. You can remove it from the WebKit browsers like this:

textarea {
  outline: none;
}

You could apply it to the :focus style as well, but it works either way. I have not yet found a way to remove it from either Firefox or Opera, but -moz-outline-style was about as far as I tested.

REMINDER: The blue glow is becoming a strong standard and breaking that standard is typically a bad thing for your users. If you do it, you should have a darn compelling reason to as well as a similarly strong :focus style.

5. Remove resize handle

WebKit browsers attached a little UI element to the bottom right of text areas that users can use to click-and-drag to resize a textarea. If for whatever reason you want to remove that, CSS is all it takes:

textarea {
  resize: none;
}

6. Add resize handle

jQuery UI has a resizeable interaction that can be used on textareas. It works in all browsers and overrides the WebKit native version, because this version has all kinds of fancy stuff (like callbacks and animation).

To use it, load jQuery and jQuery UI on your page and at its most basic level you call it like this:

$("textarea").resizable();

7. Auto-resize to fit content

James Padolsey has a super nice jQuery script for auto resizing textareas.I think that one was deleted from the internet. Here's another by Louis Lazeris, which also includes links to other options. It works just how you likely hope it does. The textarea starts out a normal reasonable size. As you type more and more content, the textarea expands to include all of that text, rather than triggering a scrollbar as is the default.

The plugin has a variety of options, but at its simplest you just load jQuery, the plugin file, and call it like this:

$('textarea').autoResize();

8. Nowrap

To prevent text from wrapping normally in CSS, you use #whatever { white-space: nowrap; }. But for whatever reason, that doesn't work with textareas. If you want to be able to type into textareas and would rather lines do not break until you press return/enter (a horizontal scrollbar is triggered instead), you'll have to use the wrap="off" attribute.

<textarea wrap="off" cols="30" rows="5"></textarea>

9. Remove default scrollbars in Internet Explorer

IE puts a vertical scrollbar by default on all textareas. You can hid it with overflow: hidden, but then you don't get any scrollbars at all when you expand. Thankfully auto overflow works to remove the scrollbar but still put them back when needed.

textarea {
  overflow: auto;
}

All the above examples can be seen here.

Comments

  1. This is one of the most informative posts Chris. I really wanted to know more about text areas and this is one of those rare posts which is solely dedicated to them :D Thanks a ton.

  2. Very, very, useful tips! Thanks! (That’s 3 very’s)

  3. jason
    Permalink to comment#

    Your awesome Chris… thanks.

  4. Batfan
    Permalink to comment#

    Good stuff to know!

  5. Leonardo
    Permalink to comment#

    I think that using jQuery for the textarea is not necessary. I’d rather use CSS pseudo-classes (Hover, active, focus…).

    • Anything that jQuery was used for in this article was specifically for something that CSS can’t do by itself.

    • You tell him ! haha

    • Permalink to comment#

      You could do the same thing with :focus, what are you talking about “css can’t do by itself”.

      Test it be my guest.
      .text {background-color:#FFF;color:#000;}
      .text:focus {background-color:#000;color:#FFF;}

    • The background image stays removed if there is text within the textarea. That text-test can only be performed with JavaScript.

    • TeMc
      Permalink to comment#

      Hm… although I admit it’s not cross-browser, but there is *:empty, right ?

    • Permalink to comment#

      js is used to determine if there’s text or not inside when the focus leaves the textarea, and returns the background only if the textarea has no text.

    • :empty, not crossbrowser thought.

  6. Wonderful article, I find it very helpful. Great information, and detail!

  7. For #4, I think that’s actually an accessibility issue for people tabbing though a form, same thing with dotted lines around links.

    But it’s OK as long as you add a :focus behavior

  8. Woow, all in once tip, thanks Chris

  9. Good stuff Chris, but just one thing: Firefox 3.6 doesn’t put any blue glow on textareas when in focus. I’d also like to point out that for your first example, it’s good to give a CSS fallback with the :focus pseudo-class.

    Other than that I will definitely be using some of these in the future, especially the auto-resize.

  10. Mateus
    Permalink to comment#

    Already discovered about half of this tricks by myself the hard way, but it’s always good to learn these little things that can make a difference for the user.

    Thanks for all these resources Chris!

  11. Check out my contact form

    http://bit.ly/b6GSWE

    It’s pretty.

  12. Wooow, huge thanks Chris!

  13. Thanks for shaing Chris!

  14. Bert de Vries
    Permalink to comment#

    Nice. Thanks. And as allways: very useable tips

    off topic: Just took a look at the website of James Padolsey and i really like the scroll effect of the background. Any ide how this is done?
    Greets

    • jQuery, thats for sure, and I think using this piece of code :)

      function(){var a=document.body,e=document.documentElement;$(window).unbind("scroll").scroll(function(){var b=Math.max(e.scrollTop,a.scrollTop)/8;a.style.backgroundPosition="0px "+-b+"px"})})();
    • Bert de Vries
      Permalink to comment#

      THX. I’ll will try this…

  15. Permalink to comment#

    Thanks for sharing. Very helpfull

  16. Thomas
    Permalink to comment#

    Some of this “tricks” are quite useful, others are not…

    1.a is nice, 1.b (removing the background on focus) can be done with textarea:focus {} background.image: none } no JS required ;)

    2./3. HTML5 rocks :)

    4. As mentioned, this should not be done…

    5. Uhm… why?

    6. /7./8./9. These Tricks are really useful :) Thanks for that!

    • @4: Many people/clients don’t like glow.
      @5: Many people try removing the resize box as sometimes, resizing ruins the layout of the design. Hence, it can be quite useful too.

  17. Permalink to comment#

    Oh man Chris, you can’t believe how much of a pain IE was to me with the overflow. I always used overflow:hidden and sort of hoped people won’t go back scrolling, because I really hated the automatic scrollbar that was always there even without any text. I totally overlooked the overflow:auto possibility. Thank you so much! much much pain saved!

  18. Permalink to comment#

    Thanks for the useful tips !

  19. Thx, Chris!
    Great article.

  20. Permalink to comment#

    Do these come with jQuery by default or is this some sort of plugin for textareas?

  21. Great article, thanks :)

  22. Markus Stange
    Permalink to comment#

    You can turn off the focus ring in Firefox by setting -moz-appearance: none, or by setting a background or border on the textarea: this will also override the native appearance.

  23. Sahan
    Permalink to comment#

    Thank You!

  24. Gurdeep
    Permalink to comment#

    cooool stuff !

    Thanks for the effort :)

  25. Yup that is interesting !

  26. Rosell
    Permalink to comment#

    Yeah well, I cannot see the point to all of this.

  27. rariox
    Permalink to comment#

    very nice… useful

  28. Chris, can I see demo?

  29. didxga
    Permalink to comment#

    A collection of tricks for Textarea, some i have not yet known. Thanks for posting it.

  30. Ilhan
    Permalink to comment#

    Nice article,
    enjoy getting tips focused on just one element

  31. Havvy
    Permalink to comment#

    These are the types of articles I enjoy.

  32. Excellent Article, Added to favs, keep up the good work.

  33. NIce tricks .. thanks for sharing Chris !

  34. Permalink to comment#

    Cheers for “resize: none;” wasn’t actually aware of this :)

  35. Instead of:
    var test = document.createElement(element);
    if (attribute in test) {
    return true;
    } else {
    return false;
    }

    You can just do:

    var test = document.createElement(element);
    return (attribute in test);

    Or maybe even:

    return (attribute in document.createElement(element))

  36. Permalink to comment#

    And finally, you put all this together, Chris!

    I spent like 2-3 days trying to find the solutions for 1, 2, 4, 5, 7, 9 back in the days….

  37. thanks for this nice tutorial :D

  38. This is strange! I was actually looking yesterday for a guide on how to do this! Thanks Chris :D

  39. prăfuitu
    Permalink to comment#

    This is simply retarded:
    $(this)[0].value

    You should use this instead:
    this.value

    this is a special keyword in JavaScript (as in many other programming/scripting languages) and it refers to the “owner” object of the currently running code. In this case, this refers to the textarea DOM object and value is one of its native properties.
    What you did is you told jQuery to take this object ($(this)), put it in a jQuery collection, access the first element of that collection ($(this)[0]) and then access the value attribute of that object ($(this)[0].value), instead of simply accessing the attribute directly (this.value), without involving jQuery into this!

    You should really learn some JavaScript and jQuery before trying to teach others anything!

    • prăfuitu
      Permalink to comment#

      And one more thing… The <code> tag is a inline tag for a reason! Wouldn’t my previous comment looked better if you’d have left the default behavior of this tag un-modified?

    • prăfuitu
      Permalink to comment#

      Pfff… Even more “awesomeness”:

      var $el = $(this);
      // console.log($el.text(), "value: " + $el.attr("val"));

      You really chose the longest way to that element’s value attribute…
      Shorter than
      $el.attr(“val”)
      would have been
      $el.val()
      or (still bad)
      $el[0].value
      or (the best)
      this.value

    • For the helpful parts of your comment:
      Awesome thanks! You’re right, I’m gonna edit the code to be more efficient like that. I actually know better, sometimes I just go fast and get it working and don’t go back and clean it up.

      For the rude parts:
      You should try and be less rude!

  40. I wasnt aware of the HTML5 placeholder tag or JQuerys resize, so many thanks for highlighting those.

  41. thanks for posting the article, picked up some tips i never realized before!

  42. Gunisigi Balaban
    Permalink to comment#

    Thanks Chris !!! That should be definitely bookmarked.

  43. Nice tips…I really learn something very important thing about textarea in context of front end

  44. This post helped me a lot ,although I was aware some of the tricks mentioned above but I Placeholder tricks was the one which I found very useful as I have touched html5 yet.

    Thanks for providing so nicely documented css tricks for textarea tag.

  45. Chrispytwist
    Permalink to comment#

    #4 on the iPhone removes the inner shadow on text boxes. Both in focus and non-focused states.

  46. I have a question about the new “placeholder” text:

    Does that text get passed in the POST/GET array if the user does not enter anything? It would really be helpful if not, otherwise it would cause extra validation when checking for blank fields that are “required” fields.

    Nice post btw!

  47. Hey Chris, thanks for sharing a couple of really nice tricks with us. I always wondered how to remove the resize handle on my boxes but never really looked into it… and now you have brought it to me. I think its going to be a case of experimenting with these examples and seeing how I get on. Cheers.

  48. Anthony
    Permalink to comment#

    Great article Chris! It’s crazy how you often manage to put up new articles just as I’m sat here scratching my head on that very subject.

    On that note…does anyone know how to make the text in a textarea ‘scroll’ without scroll bars?
    I have a styled form in which I have a containing my textarea which has a width and height set. The textarea is also set by cols/rows but in Firefox, when my typing reaches the bottom of the it continues down below the where you can no longer see what you are writing.

    Safari automatically moves the text up so the line you are writing stays visible.

    I’ve tried everything I can think of so if anyone can offer me some suggestions I’d be extremely grateful.

  49. Avkash
    Permalink to comment#

    cheers…. man
    Very Very Useful for my GUI.

    Thanks 4 sharing Chris :-)

  50. Really useful tricks – thanks for sharing;)

  51. Tommy
    Permalink to comment#

    Its important to remember that althought you can style a text area with CSS it is always necessary to include the cols and row attribute regardless
    CSS Vs cols and rows

  52. Bartdude
    Permalink to comment#

    Going into various troubles with the textarea auto resize method proposed, I found this one, which is much easier to implement and as far as I saw more cross-browser compatible : http://perplexed.co.uk/596_expanding_textarea_as_you_type.htm

  53. Permalink to comment#

    The resizer js not founs,please update your link

  54. Andy
    Permalink to comment#

    Brilliant Brilliant Brilliant article and I learnt something new about removing the glow from active fields – it looks horrible!

    One problem I’m having though is that I cannot get text to start at the top of a text-area box. I’ve tried:

    vertical-align: top !important;
    text-align: start;

    But this has no effect.

    Even tried removing ‘vertical-align: middle’ from the overall input field and changing to top but the text still appears in the middle of the area.

    What am I doing wrong?

  55. Chris -

    If you use “overflow: auto;” in the textarea, it will act like “white-space: nowrap;”.

    Just thought I’d share!

    • Andy
      Permalink to comment#

      Any ideas anybody on my problem whereby I can’t seem to make text start at the top of a text-area box instead of in the vertical center?

Leave a Comment

Current day month ye@r *

*May or may not contain any actual "CSS" or "Tricks".