Contact Form With Floating Labels in HTML and CSS
A contact section for a joinery workshop: business details on the left, a white form card on the right. Each label sits inside its box and slides up to the top edge when the field gets focus or text, so the form stays compact without losing its labels. Errors appear only after someone leaves a field, and on phones the two columns stack with the details first.
Code
import { useState, type FocusEvent, type FormEvent } from "react";
type Field = HTMLInputElement | HTMLTextAreaElement;
// Field list: change labels, types and error text here.
const FIELDS = [
{ name: "name", label: "Your name", type: "text", auto: "name", error: "Please tell us your name." },
{ name: "email", label: "Email address", type: "email", auto: "email", error: "Enter an email like [email protected]." },
] as const;
const MESSAGE_ERROR = "A sentence or two helps us quote, at least 10 characters.";
export default function ContactFormWithFloatingLabels() {
// A field only shows its error after it has been left once, like CSS :user-invalid.
const [bad, setBad] = useState<Record<string, boolean>>({});
const [sent, setSent] = useState(false);
const check = (e: FocusEvent<Field>) => setBad((b) => ({ ...b, [e.target.name]: !e.target.validity.valid }));
const recheck = (e: FormEvent<Field>) => {
const el = e.currentTarget;
if (bad[el.name] && el.validity.valid) setBad((b) => ({ ...b, [el.name]: false }));
};
const submit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
const form = e.currentTarget;
const next: Record<string, boolean> = {};
for (const el of Array.from(form.elements) as Field[]) if (el.name) next[el.name] = !el.validity.valid;
setBad(next);
const first = form.querySelector<HTMLElement>(":invalid");
if (first) first.focus();
else setSent(true);
};
// The peer classes float the label when the field has focus or text.
const box = (n: string) =>
`peer block w-full rounded-xl border bg-white px-4 pb-2 pt-6 text-[15px] text-slate-900 placeholder-transparent focus:outline-none focus:ring-4 ${bad[n] ? "border-rose-500 focus:ring-rose-100" : "border-slate-300 focus:border-teal-700 focus:ring-teal-100"}`;
const label = "pointer-events-none absolute left-4 top-2 text-xs font-medium text-slate-600 transition-all duration-150 peer-placeholder-shown:top-4 peer-placeholder-shown:text-[15px] peer-focus:top-2 peer-focus:text-xs peer-focus:text-teal-800 motion-reduce:transition-none";
const err = (n: string, text: string) => bad[n] ? <p id={`cffl-${n}-err`} className="mt-1.5 text-sm text-rose-700">{text}</p> : null;
return (
<section className="bg-[#eef3f1] px-4 py-16 sm:py-20">
<div className="mx-auto grid max-w-4xl gap-10 md:grid-cols-[1fr_1.3fr]">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.2em] text-teal-800">Saltmarsh Joinery</p>
<h2 className="mt-3 text-3xl font-semibold tracking-tight text-slate-900">Tell us about your project</h2>
<p className="mt-3 text-slate-700">Kitchens, built-in shelving and staircases across the county. We reply within two working days.</p>
<dl className="mt-6 space-y-2 text-sm text-slate-700">
<div><dt className="inline font-medium text-slate-900">Workshop: </dt><dd className="inline">Unit 4, Quay Lane</dd></div>
<div><dt className="inline font-medium text-slate-900">Phone: </dt><dd className="inline">01632 960 418</dd></div>
</dl>
</div>
<form noValidate onSubmit={submit} className="rounded-2xl bg-white p-6 shadow-sm ring-1 ring-slate-200 sm:p-8">
{sent ? (
<div role="status" className="py-10 text-center">
<p className="text-lg font-semibold text-slate-900">Thanks, your message is in.</p>
<p className="mt-2 text-slate-700">Mara will get back to you by Thursday.</p>
</div>
) : (
<div className="space-y-5">
{FIELDS.map((f) => (
<div key={f.name}>
<div className="relative">
<input
id={`cffl-${f.name}`}
name={f.name}
type={f.type}
autoComplete={f.auto}
required
placeholder={f.label}
onBlur={check}
onInput={recheck}
aria-invalid={bad[f.name] || undefined}
aria-describedby={bad[f.name] ? `cffl-${f.name}-err` : undefined}
className={box(f.name)}
/>
<label htmlFor={`cffl-${f.name}`} className={label}>{f.label}</label>
</div>
{err(f.name, f.error)}
</div>
))}
<div>
<div className="relative">
<textarea
id="cffl-message"
name="message"
rows={4}
required
minLength={10}
placeholder="What would you like built?"
onBlur={check}
onInput={recheck}
aria-invalid={bad.message || undefined}
aria-describedby={bad.message ? "cffl-message-err" : undefined}
className={`${box("message")} resize-y`}
/>
<label htmlFor="cffl-message" className={label}>What would you like built?</label>
</div>
{err("message", MESSAGE_ERROR)}
</div>
<button type="submit" className="h-12 w-full rounded-xl bg-teal-800 text-[15px] font-semibold text-white hover:bg-teal-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-teal-800 focus-visible:ring-offset-2">Send message</button>
</div>
)}
</form>
</div>
</section>
);
}
Install with one command: npx shadcn@latest add https://we.inc/r/contact-form-with-floating-labels-html-css.json
When to use it
- A small business site needs a short enquiry form with name, email and message.
- Space is tight and stacked labels above every box would make the form look long.
- You want a form that still posts and validates if the page script never loads.
- The design calls for one accent colour carried through focus rings, labels and the button.
How to customize it
- Edit the `FIELDS` array to add a phone field; give it `type: "tel"` and `auto: "tel"` so phones show the number pad.
- Change the accent by replacing `teal-800` and `teal-100` in React, or `--cff-accent` in the CSS version.
- Set the form `action` to your form handler address and keep `method="post"` in the plain version.
- Adjust `minLength={10}` on the message box, or remove it if a short note is fine.
Accessibility
- Every field has a real label element that stays visible after it floats, and the placeholder is transparent so it never doubles the label.
- Error text is tied to its field with aria-describedby and the field is marked aria-invalid, so the reason is read when focus returns.
- On a failed submit, focus moves to the first invalid field instead of leaving people to hunt for it.
Questions
How do floating labels work in pure CSS?
Give the input a placeholder, make the placeholder transparent, and place the label after the input. The selector :placeholder-shown:not(:focus) + label matches only while the field is empty and unfocused, so that rule drops the label into the box; at every other moment it sits at the top.
Why put the label after the input in the HTML?
CSS can only style an element based on a sibling that comes before it. Putting the label after the input lets the input's state choose the label's position, and absolute positioning moves it visually above the text.
What does :user-invalid add over :invalid?
It waits until the person has changed the field or tried to submit, so an untouched form does not open covered in red. In browsers without it, the script sets aria-invalid on blur and the same styles follow that attribute.
How do I send the form without a back end?
Point the form action at a form service or a serverless function that emails you. Keep the field names the same, because the service reads them as the keys of the message it sends.
Will this layout work with a dark background?
Yes, if you change the card, field and label colours together. Check the floated label against the field background, since small text needs a contrast of at least 4.5 to 1.
Related: HTML Form Examples with Every Input Type, Copyable as HTML + CSS or Tailwind, Signup Form With Inline Validation Messages, Two Column Booking Form With Select and Date.
More forms or all free UI components. Build your site free to have a full site built around it.
More in Forms
- HTML Form Examples with Every Input Type, Copyable as HTML + CSS or Tailwind
- Paper Cheque Payment Form That Writes the Payee, Amount in Words and Signature in Pen as You Type
- Photoreal Login Page HTML CSS with Show Password, Remember Me and a Cut Glass Door Knob in Window Light
- Pin Tumbler Lock Cutaway Password Strength Field Where Each Rule Sets a Pin and the Key Turns the Plug
- Ray-Marched Brass Hotel Key Sign-In Form Where the Key Swings Toward a Lock Case on Green Leather as You Type and Throws the Bolt on Submit
- Restaurant Reservation Book Time Picker with a Pencil on a String That Writes Your Table into a Free Line
- Signature Pad on Cotton Paper with a Fountain Pen That Leaves Wet Ink Which Dries
- Barbershop Appointment Card Rack Time Slot Picker Where Your Card Lifts Out and Drops into a Free Hour Pocket
Product
Who It's For
- For Agencies
- For Freelancers
- For Hosting Providers
- For SaaS Platforms
- For Startups
- For Financial Services
- For Healthcare
Features
Resources
- Blog
- Help Center
- Free Business Tools
- Free UI Components
- Website Templates
- Template Collections
- Website Examples
- Guides
- Comparisons
- Alternatives
- Best Lists
- Reviews
- Pricing Guides
- Use Cases
- Glossary & Guides
- Integrations
- Developers
- Benchmark
- Windows App