Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to add an outline

Short answer

outline draws a line around an element without changing its size:

<div style="display: flex; gap: 12px;">
  <div style="padding: 12px; background: lavender; outline: 3px solid royalblue;">outline</div>
  <div style="padding: 12px; background: lavender; border: 3px solid royalblue;">border</div>
</div>

border is part of the box size, and adding it shifts the neighbors. outline is drawn on top and takes no space.

Spacing from the element

outline-offset moves the outline outward (or inward with a negative value):

<button style="margin: 12px; outline: 2px dashed crimson; outline-offset: 4px;">Outlined button</button>

A focus outline

The main job of outline is showing where keyboard focus is. Press Tab:

<style>
  .btn:focus-visible { outline: 3px solid orange; outline-offset: 2px; }
</style>
 
<button class="btn">First</button> <button class="btn">Second</button>

:focus-visible shows the outline for keyboard users and hides it on mouse clicks.

Common mistake

outline: none on everything "to remove the ugly frame". After that a keyboard user cannot see where they are and cannot use the site. Do not remove the outline; replace it with your own via :focus-visible.

Functions used in this recipe

  • outline — An outline around the element that takes no space and does not shift neighbors.
  • :focus-visible — Matches a focused element when the browser decides the focus should be visible — usually after keyboard navigation.
  • box-shadow — A shadow around the element's box.
  • border — A border around the element: width, style and color in one property.

Thanks for reading!

Donate to the site — we work hard for you.