CSS3 Beginner Selectors · 6 min read

CSS outline and outline-offset

Lesson 33 of 41 in the CSS3 learning path.

How do I draw a focus ring that does not shift layout?

outline is drawn outside the border box and does not take up space in the layout.

A focus ring made of border or padding moves the button. outline does not.

Syntax & Parameters

Syntax
button:focus-visible { outline: 2px solid #1d4ed8; outline-offset: 3px; }

Example

Interactive preview available
focus.css
button {
  font: 600 1rem sans-serif;
  padding: .5rem 1rem;
  border-radius: 8px;
  border: 0;
  background: #1d4ed8;
  color: white;
}
button:focus {
  outline: none;
}
button:focus-visible {
  outline: 2px solid #1d4ed8;
  outline-offset: 3px;
}

Expected Output

Tabbing to the button shows a blue ring 3 pixels outside it. Clicking with a mouse does not leave that ring.

Line-by-Line Walkthrough

  1. The button has no layout border.
  2. focus clears the default outline only because focus-visible replaces it.
  3. focus-visible draws a 2 pixel solid ring.
  4. outline-offset leaves a 3 pixel gap so the ring is not stuck to the radius.
  5. The ring does not change the button width.
  6. Mouse clicks usually do not show focus-visible.
  7. Keyboard tab does.
  8. Never leave focus with no replacement ring.

Common Pitfalls & Security

Watch the failure mode, not only the happy path.

  • outline: none on focus with no focus-visible rule removes the keyboard indicator.
  • outline-offset can be clipped by a parent with overflow hidden.
  • A ring that matches the background is invisible.
  • Do not use outline to fake a border on every button. It is a focus tool here.

Best Practices & Modern Standards

Style :focus-visible, not every :focus, when you want mouse clicks to stay quiet.

Keep a 2 pixel ring with a 3 pixel offset and a color that passes against both the button and the page.

Real-World Use

The catalog Save button keeps a visible ring for keyboard users and does not jitter when the ring appears.

Frequently Asked Questions

Does outline affect layout?

No. It is drawn outside the box and does not take space.

Why offset the ring?

So a rounded button still shows a gap between the fill and the ring.

Is outline none ever safe?

Only when a :focus-visible rule immediately replaces it.

What about high contrast mode?

A solid outline is more reliable than a box-shadow glow.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…