Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to style input fields

Short answer

Give the field a border, padding, rounding and font, and change the border color on focus:

<style>
  .field { padding: 10px 12px; border: 1px solid silver; border-radius: 8px; font: inherit; }
  .field:focus { border-color: steelblue; outline: 3px solid lightblue; }
</style>
 
<input class="field" type="text" placeholder="Your name">

font: inherit matters: by default fields use their own system font and size, different from the page text.

A full-width field

To make the field take the full form width without overflowing because of the padding, add box-sizing: border-box:

<style>
  .field { box-sizing: border-box; width: 100%; padding: 10px 12px; border: 1px solid silver; border-radius: 8px; font: inherit; }
</style>
 
<form style="display: grid; gap: 8px; max-width: 300px;">
  <input class="field" type="email" placeholder="Email">
  <textarea class="field" rows="3" placeholder="Message"></textarea>
</form>

All fields at once

To avoid putting a class on every field, use a type selector: input:not([type="checkbox"], [type="radio"]), textarea, select. Checkboxes and radio buttons are styled differently, so they are excluded.

Common mistake

The field gets width: 100% and padding, but not box-sizing: border-box. The padding is added to the width, and the field sticks out past the right edge of the form:

<div style="width: 240px; border: 1px dashed tomato;">
  <input type="text" placeholder="Too wide" style="width: 100%; padding: 10px;">
</div>

Functions used in this recipe

  • <input> — An input field; its kind is set by the `type` attribute.
  • <textarea> — A multi-line text field.
  • border — A border around the element: width, style and color in one property.
  • :focus — Matches the element that currently has focus: a field being typed into, a button selected with Tab.
  • box-sizing — Whether `width` and `height` include the padding and the border.

Thanks for reading!

Donate to the site — we work hard for you.