Does anyone know how to style this button?
I tried this which doesn't work quite as I expected
6 Replies
The first one is the result I want to achieve (designed in figma), the second one is the code above I tried
The shadow unfortunately only renders where it would be visible outside of the current element, so you can't use a simple box shadow like that.
There's two options I can see, you can either use some stacked shadows including inset ones, or you can use a pseudo element.
Stacked shadows have the disadvantage that you need to set the background color to match the background of the A's parent, so it won't work over complicated backgrounds. The reason for this is that if you use
transparent
as the first color, it'll just show the next layer of shadow underneath.
The pseudoelement has the disadvantage that it needs different HTML. You have to put the pseudoelement on the direct parent, which is then set to be as wide as its content. You also need to control the height of the fake shadow somehow, I'm using padding here because it gave me the best results.
The reason you need to use a separate element is because of stacking context. If you position and translate a pseudoelement on the A itself, it creates a new stacking context which makes it impossible to put it underneath the element it's on.
The first example in the codepen is just showing why the regular shadow doesn't work. You can see that there's just a transparent background on the A, so it's showing the red background of its parent.
https://codepen.io/jochemm/pen/XWybezR?editors=1100@suhaylmv here's some more info about stacking context https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_positioned_layout/Understanding_z-index/Stacking_context and
box-shadow
https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadowThank you @jochemm so much for your effort!
I chose the pseudoelement option and works fine, but when I try to move <a> when pressed it doesn't work
translate doens't work on inline elements, you'll have to set the A to be
inline-block
instead. You can also drop the padding on the parent thenOh, forgot about that
Thanks