119

Is it possible to set transparency on the box shadow?

This is my code:

  box-shadow:10px 10px 10px #000;
  -webkit-box-shadow:10px 10px 10px #000;
  -moz-box-shadow: 10px 10px 10px #000;
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Steven
  • 19,224
  • 47
  • 152
  • 257

1 Answers1

222

I suppose rgba() would work here. After all, browser support for both box-shadow and rgba() is roughly the same.

/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);

div {
    width: 200px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    color: white;
    background-color: red;
    margin: 10px;
}

div.a {
  box-shadow: 10px 10px 10px #000;
}

div.b {
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);
}
<div class="a">100% black shadow</div>
<div class="b">50% black shadow</div>
Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 3
    Worked for me and solved the enormous problem that color-based shadows only work for a given background, so you need to restyle them depending on what they'll be over which often isn't possible (a div that covers both a photo and white bg, in which case shadow looks pale on top of photo) – jerclarke Dec 16 '13 at 17:56
  • @jeremyclarke I was experiencing the same issue where I needed a button's shadow to work on multiple background colours without having to define a unique shadow colour for each background. Transparent black works like a true shadow. – Clarus Dignus Feb 22 '15 at 12:55
  • 3
    rgba() does not work for me, if I want to change chrome's `input:-webkit-autofill` – Samuel Jul 26 '16 at 11:44
  • It's always Chrome, isn't it. – BoltClock Jul 26 '16 at 11:55
  • But what if one wants to set only the transparency/opacity of the shadow (which was the original question)? Independent of the color (which may be given as a named color for example). – Chris K May 01 '18 at 13:06
  • 1
    @Chris K.: I'm afraid you won't be able to do this separately from the original box-shadow declaration. The closest you can get is with rgba() and CSS variables, but that means no support for named colors, and you have to apply the variables to the box-shadow declaration itself. background-color has a similar limitation, covered [here](https://stackoverflow.com/questions/6962432/is-it-possible-to-change-only-the-alpha-of-a-rgba-background-colour-on-hover/6962502#6962502). Also see https://stackoverflow.com/questions/40010597/how-do-i-apply-opacity-to-a-css-color-variable/41265350#41265350 – BoltClock May 01 '18 at 13:10