DEV Community

Alex Carpenter
Alex Carpenter

Posted on

Better CSS outlines with box-shadows

I think we can all agree that the default browser outline styling isn't the most beautiful design implementation. I also think we can agree that it may not be pretty but it does function well.

It can be common to see folks remove the outline completely and not replace it with any other visual indication. This is bad practice and can hurt the user experience for keyboard users.

To appease our designers while keeping our site accessible, lets remove the default outline style and replace it with a box-shadow implementation shown below.

input:focus {
  outline: 0;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, .5);
}
Enter fullscreen mode Exit fullscreen mode

So we can see we set the outline to 0 when the input is focused and added a box-shadow declaration to replace its functionality. As an added bonus, using a box-shadow also follows border-radius declarations. So if our input has a 4px border radius, our faux outline will not have a gap in the corners.

Check out the CodePen example to see it in action.

Top comments (6)

Collapse
 
revisionaccess profile image
revisionaccess

The box-shadow property should not be used on its own to provide focus indicators, as an outline implemented with this property is not visible to users with High Contrast Mode enabled. Either the outline or, better yet for design purposes, the border property should be used instead.

Collapse
 
jordihoven profile image
Jordi Hoven

love it! i love the ux of an outline, but hate how modern browsers handle it. looks like any non-chromium browser does not add a border-radius, making it break ui consistency. i removed all my outlines, and added your box-shadow style and it works like a charm!

Thanks <3

  • jordi
Collapse
 
theluk profile image
Lukas Klinzing

Consider not resetting outline but setting color to transparent. This will ensure compatibility with high contrast mode

Collapse
 
bboydflo profile image
Florin Cosmin

nice, thanks for this. super useful!

Collapse
 
lucasromerodb profile image
Luke • Edited

Nice tip. You can manage the element's z-index to avoid overlap.

Collapse
 
adam_cyclones profile image
Adam Crockett πŸŒ€

That was handy just to have a snippet.