How to set inner shadow on text in CSS (in webkit…)

October 26, 2012

Unlike the box-shadow property, inner-shadow does not support the inset attribute. The following code is NOT valid:

 text-shadow: inset 0px 0px 10px rgba(0,0,0,0.9);

Which is a bummer, I really wanted to style the logo of my site in CSS and not use an image, font or SVG for it. But I came over a clever hack that solves the issue for us.

How it works

There are 5 steps that are needed to acheive this, and you can see the result of each of them below:

.logo{
  font-size: 4em; /*step 1*/
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2); /*step 2*/
  color: transparent;/*step 3*/
  background-color: #F9F9F9;/*step 4*/
  background-clip: text;/*step 5*/
}

How it works:

  1. 1. The normal style without any applied effects
  2. 2. The text when a black shadow with opacity applied
  3. 3. We hide the text the only thing visible is the shadow
  4. 4. We set the background color to the color we want the text in
  5. 5. We clip the background to the bounds of the text. This will make the shadow look like it is just on the inside of the text!

Support

Background is a webkit specific property at this point.

UPDATE: Turns out it is tricky to feature test this unless you want to browsersniff. Modernizr has not yet found a good solution: https://github.com/Modernizr/Modernizr/issues/199

Happy coding!

Categorised in: ,

Written by Anders M. Andersen

  • iamvdo

    Cool, but background-clip: text is only Webkit compatible and isn’t present on any part of W3C spec. :(

  • Anders Andersen

    Thanks, post updated.

  • denbuzze

    Thanks Anders for posting this, I added a JSFiddle at http://jsfiddle.net/denbuzze/vdLTL/

  • denbuzze

    Thanks Anders for posting this, I added a JSFiddle at http://jsfiddle.net/denbuzze/vdLTL/

  • http://amobil.se Anders M. Andersen

    Thanks! I updated it with background color and webkit vendor prefix: http://jsfiddle.net/andmag/QsZs8/

  • http://amobil.se Anders M. Andersen

    Thanks! I updated it with background color and webkit vendor prefix: http://jsfiddle.net/andmag/QsZs8/

  • Pingback: Today’s Readings | Aaron T. Grogg()

  • http://roparz.me/ Roparz

    I tried to do the same with an image as text background :
    http://cssdeck.com/labs/cca4hwqo

  • http://roparz.me/ Roparz

    I tried to do the same with an image as text background :
    http://cssdeck.com/labs/cca4hwqo

  • Felix Kiunke

    That’s pretty clever, though since background-clip is a webkit-only property which isn’t even in the specs, maybe SVG would be an option? This could easily be achieved with SVG filters :)

  • Felix Kiunke

    That’s pretty clever, though since background-clip is a webkit-only property which isn’t even in the specs, maybe SVG would be an option? This could easily be achieved with SVG filters :)

© 2014 Copyright.