Seth is currently live on Twitch! Go There Now?
October 30, 2019
Advice I Wish I Could Take For Myself
Text Area With 100% Width With Borders And Padding

This was something that I just recently figured out. For years my CSS was this:

  • <textarea></textarea>
  • <style>
  • textarea{
  • border: 1px solid #000;
  • padding: 5px;
  • /* border-left (1) + border-right (1) + padding-left (5) + padding-right (5) = 12 */
  • width: calc(100% - 12px);
  • }
  • </style>

This is a solution, but it's rather messy. You can't change the border size or padding without having to calculate what to put in the little width: calc(); function. For years I thought that that was the best option. Silly me. Check out this solution.

  • textarea{
  • border: 1px solid #000;
  • box-sizing: border-box; /* tells browser to take border and padding size into width consideration */
  • padding: 5px;
  • width: 100%;
  • }

Bam! Add the box-sizing: border-box; into the stylesheet and the 100% width will take the padding and border size into consideration when sizing the element. This is crazy, I never knew this, and I've been doing this for a long time. Definitely will switch all of my inputs to this way of sizing.

The only caveat is that it doesn't take margins into consideration. So if you're using margins with float: left; or float: right; boxes that have % values, you'll still have to use calc(100% - margins); to get the right width that you're looking for. Still, it's a cool solution for a problem that I've had for years.

 Profile Picture
Comment