Explain Codes LogoExplain Codes Logo

How to get box-shadow on left & right sides only

html
responsive-design
css
performance
Nikita BarsukovbyNikita Barsukov·Jan 3, 2025
TLDR

To get a shadow on the left and right sides only, use the box-shadow CSS property. Apply negative offsets for the left shadow and positive offsets for the right, with large spreads and no vertical offset.

.element { box-shadow: inset -5px 0 5px -3px rgba(0,0,0,0.3), inset 5px 0 5px -3px rgba(0,0,0,0.3); /* Left and Right shadow, nailed it! */ }

Tweak RGBA values for custom color and opacity, and pixels for adjusting the shadow's spread and intensity.

Hacks for target precision

Multiple shadows for clean edges

To avoid the unintended top and bottom shadows, you can apply extra box-shadow layers with negative spreads that eat away the undesired part, like a code-ninja 🐱‍💻:

.element { box-shadow: inset -5px 0 5px -3px rgba(0,0,0,0.5), inset 5px 0 5px -3px rgba(0,0,0,0.5), 0 -5px 5px -3px rgba(0,0,0,0), /* Ghost shadow */ 0 5px 5px -3px rgba(0,0,0,0); /* Another ghost shadow */ }

This assures clean edges by matching the background color with the shadow color, basically the shadow is hiding in plain sight! 😎

Pseudo-elements for shadow isolation

Using the ::before and ::after pseudo-elements can give you an extra level of control over your shadows, it's like having shadow mini-me(s)! 👥:

.element::before, .element::after { content: ''; position: absolute; top: 0; bottom: 0; width: 10px; box-shadow: 0 0 5px #333; /* Mini-me shadow */ z-index: -1; } .element::before { left: -10px; /* Shadow on the left */ } .element::after { right: -10px; /* Shadow on the right */ } .element { position: relative; overflow: hidden; /* Hide the overflow. Duh. */ }

Clip-path for shadow molding

The clip-path property shapes up our shadow like a barber trimming hair. It cuts off unwanted parts while also being able to give a unique silhouette.

.element { box-shadow: -10px 0 15px rgba(0,0,0,0.5), 10px 0 15px rgba(0,0,0,0.5); /* Regular two-sided shadow */ clip-path: inset(0 0 0 0 round 10px); /* The moot barber */ }

Leveling up with shadows

Cross-browser harmony

Your shadow might not look the same across various browsers. So, make sure your chosen shadow calibrates well with your design objectives and withstands the acid tests of browser compatibility.

Image-based solutions: The dark side

While they might serve a purpose, they turn out to be the slow turtles of the web. Stick to CSS solutions for snappy, adaptable, and hi-perf results.

Experiment. Fail. Learn.Repeat

Stay creative. Discover extraordinary designs through tinkering with values and methods. A daring departure can sometimes beget the most stunning visual results!