Border vs OutlinePosted on Jun 16, 2014 by Nate in Uncategorized
Not long ago, I was working on a site for a client, and the designer wanted to implement something that I initially assumed would be very simple. He wanted to use a full-width background image for the site and show all the content in a smaller div centered on the page. Pretty standard. But he wanted the content div to have a transparent border so that the background image would still be visible underneath. I thought that would be simple enough, so I added this line of CSS to the content div:
border: 7px solid rgba(255, 255, 255, 0.2);
This image shows the result (the black section represents the content area). Instead of being transparent, the border was completely white. Why wasn’t the background showing through? I initially thought that the border property must not allow transparencies, but I soon found out that wasn’t the case.
By applying a background color to the content div, I could see that the border was applying the transparency correctly, as exhibited by the slightly lighter color. My real problem was that the border attribute takes up space — the content is forced to move in just a bit to account for the border. This means that the border shows on top of the edge of the content div and does not hang over the parent div as I initially assumed it did.
At this point, I really wasn’t sure what to do in order to make the site look just like the original design. And then I remembered the outline property. After finding a StackOverflow article about it, I removed my border setting and used the same values for outline:
outline: 7px solid rgba(255, 255, 255, 0.2);
I finally had the result I was looking for. The outline property takes up no space, just like an element with ‘fixed’ or ‘absolute’ positioning, so it won’t alter any margin or padding settings that you have in place. Instead of taking up an element’s interior space like the border property, outline exists outside the element.
While outline’s primary use deals with accessibility in that it shows which element has keyboard focus, the use I’ve outlined above shows how you can achieve some really cool results by occasionally using it as an element of your design.