A Web Design Community curated by Chris Coyier

Textarea Tricks

By: Chris Coyier on 7/16/2010

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. 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.

80 Responses

  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 says:

    Your awesome Chris… thanks.

  4. Batfan says:

    Good stuff to know!

  5. Leonardo says:

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

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

  7. Tim Wright says:

    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. Yoosuf says:

    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 says:

    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. David says:

    Wooow, huge thanks Chris!

  13. Thanks for shaing Chris!

  14. Bert de Vries says:

    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"})})();
  15. Olli says:

    Thanks for sharing. Very helpfull

  16. Thomas says:

    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. Amit says:

    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. Theo says:

    Thanks for the useful tips !

  19. Anton says:

    Thx, Chris!
    Great article.

  20. Chad says:

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

  21. Nikki says:

    Great article, thanks :)

  22. Markus Stange says:

    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 says:

    Thank You!

  24. Gurdeep says:

    cooool stuff !

    Thanks for the effort :)

  25. Yup that is interesting !

  26. Rosell says:

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

  27. rariox says:

    very nice… useful

  28. Galer says:

    Chris, can I see demo?

  29. didxga says:

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

  30. Ilhan says:

    Nice article,
    enjoy getting tips focused on just one element

  31. Havvy says:

    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. Nick says:

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

  35. Daniel15 says:

    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. Webo says:

    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 says:

    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 says:

      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 says:

      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. perth web says:

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

  42. Gunisigi Balaban says:

    Thanks Chris !!! That should be definitely bookmarked.

  43. Mansur says:

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

  44. Yogendra says:

    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 says:

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

  46. Randy says:

    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 says:

    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 says:

    cheers…. man
    Very Very Useful for my GUI.

    Thanks 4 sharing Chris :-)

  50. Rafal says:

    Really useful tricks – thanks for sharing;)

Leave a Comment

Remember:
  • Be nice.
  • Wrap multiline code in <pre> and <code> tags and escape it first (turn <'s into &lt;'s).
  • You may use regular HTML stuff like <a href="">, <em>, and <strong>
* This website may or may not contain any actual CSS or Tricks.