Create Crisp Image Borders With CSS Pseudo Elements
Transparent image borders can have contrast issues and look dull, let’s make them nice and crisp with this tiny CSS trick.
The demo below shows a default half transparent image border.
We can see that we lose contrast depending on the colors of the image near the border.
The border looks nice when it’s near a contrasting area, but it kind of dissapears when near colors of the same brightness.
In the example below we overlay the border on top of the image, this creates a very nice sharp edge.
The side-by-side comparison below makes it more clear.
For this CSS trick we use an inset box-shadow
instead of a border
, while an image can have an inset box-shadow it won’t show as that’s where its pixels are rendered.
So to do this we’ll have to overlay another element on top. Let’s set up the HTML.
<div class="fancy-border">
<img src="cat.jpeg" alt="" />
</div>
We’ll scale the .fancy-border
element to be as wide as the image.
Next we create a Pseudo Element with an inset box-shadow
and overlay it on top of the image.
Finally we set pointer-events
to none
to hide the Pseudo Element element from user interactions.
.fancy-border {
position: relative;
width: fit-content;
border-radius: 1rem;
}
.fancy-border img,
.fancy-border::after {
border-radius: inherit;
}
.fancy-border img {
display: block;
}
.fancy-border::after {
content: '';
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.25);
pointer-events: none;
}