7

Is it possible to add a border to a box-shadow?

I want to create a class with a coloured offset with that offset being outlined in a black border.

Now I know I can create a div and offset it to get this desired look, but I want to know if it's possible to do it without so I can just create a class and add it to the divs that I want to do this too.

I attached a snippet showing the colour offset but I would like the red offset to be outlined in a black border.

.example-div{
  width: 100px;
  height: 100px;
  border: 1px solid black;
  box-shadow: -5px 5px red;
}
<div class="example-div">
</div>

3 Answers3

10

You can add additional box-shadows to your div to get that effect. For your case update your box-shadow property to something like this

box-shadow: -5px 5px red, 
    -5px 5px 0px 3px black;

This resource has tons of more info about box-shadows and it's syntax https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow if you want to follow.

Shubh Sheth
  • 411
  • 5
  • 15
2

You can add a CSS pseudo-element to your class which automatically will add another object behind the main object on each element which has that class. Use absolute position, a negative z-index, 100% width and height and determine the offset with the left or right and bottom or top parameters as in this example:

(note: You need a non-transparent background for the main element when you use this method)

.example-div {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  position: relative;
  background: #fff;
}
.example-div::after {
  content: '';
  position: absolute;
  z-index: -1;
  left: -5px;
  bottom: -5px;
  width: 100%;
  height: 100%;
  background: red;
  border: 1px solid black;
}
<div class="example-div">
</div>
Johannes
  • 64,305
  • 18
  • 73
  • 130
1

CSS outline and border aren't going to be much help unfortunately, as the box-shadow doesn't really exist and those will still target the element's bounding box (which is unaffected by the box-shadow).

You could make use of ::before or ::after, but that gets a little complicated for what you're trying to do.

One thing you could do is make use of multiple box-shadows. box-shadow takes a comma separated list of shadows, and it's supported in all majors browsers. The trick here would be to make use of the 4th (underutilized IMHO) parameter for box-shadow, called spread-radius. This will "spread" (expand) or "choke" (shrink) the box shadow's reference frame by that many pixels before the blur radius is applied.

In your case, for a 2px wide "border" around the box-shadow, you could do the following:

.example-div {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  box-shadow: -5px 5px red, -5px 5px 0 2px blue;
}
<div class="example-div"></div>
Xhynk
  • 13,513
  • 8
  • 32
  • 69