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
button:focus-visible { outline: 2px solid #1d4ed8; outline-offset: 3px; }
Example
Interactive preview availablebutton {
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
- The button has no layout border.
- focus clears the default outline only because focus-visible replaces it.
- focus-visible draws a 2 pixel solid ring.
- outline-offset leaves a 3 pixel gap so the ring is not stuck to the radius.
- The ring does not change the button width.
- Mouse clicks usually do not show focus-visible.
- Keyboard tab does.
- 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.