masterchefsenior masterchefsenior - 6 months ago 22
HTML Question

want to avoid hiding previous li elements with CSS box-shadow

I have a list where each element has a box shadow behind it to make it stand out against some background:



html {
background: black;
}

span {
background: white;
box-shadow: 2px 0 0 white, -2px 0 0 white, 2px 10px 0 white, 2px 20px 0 white, 2px 30px 0 white, 2px 40px 0 white, 2px 50px 0 white;
}

<ul>
<li><span>California</span></li>
<li><span>Idaho</span></li>
<li><span>Maine</span></li>
<li><span>Oregon</span></li>
</ul>





However, if I try to make the box shadow project up instead of down, it covers the previous element's text:



html {
background: black;
}

span {
background: white;
box-shadow: 2px 0 0 white, -2px 0 0 white, 2px -10px 0 white, 2px -20px 0 white, 2px -30px 0 white, 2px -40px 0 white, 2px -50px 0 white;
}

<ul>
<li><span>California</span></li>
<li><span>Idaho</span></li>
<li><span>Maine</span></li>
<li><span>Oregon</span></li>
</ul>





Is there any way to avoid this, and have the box shadow always behind the text? Thanks.

Answer

Every solution I can think of has some unfortunate compromise.

The boring, not-very-extensible, answer is to use a descending z-index. You can automate this with a preprocessor like SASS (if you know the maximum number of items in advance) or JavaScript; let me know if you want to do either.

html {
  background: black;
}

span {
  background: white;
  box-shadow: 2px 0 0 white, -2px 0 0 white, 2px -10px 0 white, 2px -20px 0 white, 2px -30px 0 white, 2px -40px 0 white, 2px -50px 0 white;
}

li {
  position: relative;
  z-index: 4;
}

li:nth-child(2) {
  z-index: 3;
}

li:nth-child(3) {
  z-index: 2;
}

li:nth-child(4) {
  z-index: 1;
}
<ul>
  <li><span>California</span></li>
  <li><span>Idaho</span></li>
  <li><span>Maine</span></li>
  <li><span>Oregon</span></li>
</ul>

Alternatively, if you're willing to invert the order of your list items in your markup (grim, but possibly acceptable), you can use flexbox—specifically the flex-direction property—to reverse the order in which elements are oriented along the main axis.

html {
  background: black;
}

ul {
  display: flex;
  flex-direction: column-reverse;
}

span {
  background: white;
  box-shadow: 2px 0 0 white, -2px 0 0 white, 2px -10px 0 white, 2px -20px 0 white, 2px -30px 0 white, 2px -40px 0 white, 2px -50px 0 white;
}
<ul>
  <li><span>Oregon</span></li>
  <li><span>Maine</span></li>
  <li><span>Idaho</span></li>
  <li><span>California</span></li>
</ul>

Comments