Hi! This is the second post in my TIL series, where I'm sharing small things that I've learned recently. With this post, I'm going to cover a method I've recently used for putting a straight border on an HTML element with rounded corners.
I was building out a "card" element for a website, and it had that typical card styling: some rounded corners, and a bit of a box shadow to create some depth. While reading through Refactoring UI: The Book I got to the "Finishing Touches" section. In that section, the book suggested adding accent borders to things for a pop of color. It looks neat, so I decided to go for it.
This isn't a trick question. It's usually one of the first things that a web developer will learn when they're starting to play with CSS. You use the
border property if you want all the borders to be the same. Otherwise, you'll use some combination of the side-specific border properties:
The card element has a
border-radius set on it to achieve the rounded corners we want. As a result though, the border follows the curvature of the corners. If this is desirable for you, then there's no problem. What I wanted though, was a straight line "accent" that mimicked a border.
I ended up using pseudo-elements to achieve the desired accent effect. With absolute positioning, and hiding overflow on the card, I was able to make an accent line that didn't curve with the card's corners. There's a CodeSandbox demo below with the working solution.
This CodeSandbox has a demo of the problem and the solution.
- I think the straight accent line looks nicer than the curved border.
- Using the pseudo-element unlocks extra animation options if we want them (slide in, expand outward, etc.)
- The solution introduces positioned elements. This may cause some layering problems depending on the elements around it. Unlikely, but possible. (See The stacking context and position)
- The element with the accent line needs to have its overflow hidden. It's fine in this use case, but may not be in others.
- It does require more code than using a regular border.
This solution ended up working out well for me. It allowed me to achieve what I believe is a more desirable look without too much more code. I realize that the cons list is longer than the pros list, but the tradeoff is worth it for me. The scarier cons about positioning and overflow only apply in specific situations that seem unlikely.
Also, I mentioned Refactoring UI: The Book earlier. I'd highly recommend it, but it is a bit on the pricey side (see if your employer has an education budget). I've found it to be a great resource for developers looking to improve their web design skills with practical examples.