← All Examples

Character Count Indicator

Input border changes color based on validity using :user-invalid and :user-valid with minlength/maxlength.

Published June 11, 2026

Demo

Min 2 characters Max 40
Min 20 characters Max 160

HTML

<input type="text" minlength="2" maxlength="40" placeholder="Enter your name">
<div class="cc-meta">Max 40 characters</div>

CSS

input:user-valid {
  border-color: var(--teal);
}

input:user-invalid {
  border-color: var(--coral);
}

input:user-valid ~ .cc-meta {
  color: var(--teal);
}

input:user-invalid ~ .cc-meta {
  color: var(--coral);
}

How it works

CSS alone can't read the live character count, but it can style inputs based on validity constraints. maxlength prevents typing past the limit. minlength sets the minimum. The :user-valid and :user-invalid pseudo-classes fire only after the user has interacted with the field — preventing red borders on untouched inputs. The sibling ~ combinator lets the hint text change color to match.