CSS "realistic" shadows (light source)
Asked Answered
J

3

11

Have a look at the picture below:

skyscrapers

The blue boxes are divs. Now what I am trying to do is to implement a sort of 2.5D functionality:

I would like the grey shadows to be somewhat 3D-ish. At first I was thinking to assign to the box-shadow value the "Y" axis like this:

"box-shadow: -5px -5px 10px" + value.tallness +  "#888"

but the result is the above image.

Any idea on how to make the shadow on one side only, like there was a light source from somewhere?

EXTRA - what about a moving "light source"?

Jereme answered 19/8, 2012 at 14:14 Comment(2)
I am working on an example on jsfiddle. Trying to make the moving light source :DScrophulariaceous
If you don't mind using a plugin realshadows.js is really good. jsfiddle.net/AA69GAlignment
S
22

There you go: http://jsfiddle.net/KaCDN/15/

Drag light source to affect shadows.

Taller blocks:

  • have larger top,left border
  • drop shadow further
  • they're shadow is blurier
Scrophulariaceous answered 19/8, 2012 at 14:50 Comment(7)
Updated: taller blocks have a lighter color.Scrophulariaceous
Update2: Taller blocks drop shadow further than shorter blocks.Scrophulariaceous
Hmm, one problem is that the shadow from one div appears on top of another div. Don't know if it's possible to make the shadows be bottom-most, as long as they're created using box-shadow.Scrophulariaceous
Update: Distance between light source and block affects shadow's size.Scrophulariaceous
that code seems so complicated! a great example by the way! I really got no clue where to start modifying it, aha. where do i change shadow color (they seem a bit too white-ish) and "definition"? so that the shadow border is less blurry?Jereme
I'll add comments to the code to make it easier to understand.Scrophulariaceous
There you go, added some comments.Scrophulariaceous
C
4

How to move the shadow a little simpler:

$(document).on('mousemove', function(e) {
    var elm = $("#test"),
        x = ~Math.round((e.pageX - elm[0].offsetLeft - 150) / 30),
        y = ~Math.round((e.pageY - elm[0].offsetTop - 150) / 30),
        z = 10+Math.abs(x)+Math.abs(y),
        cssVal = x+'px '+y+'px '+z+'px 10px #525252';

    elm.css({'-webkit-box-shadow' : cssVal, 'box-shadow' : cssVal });
});

FIDDLE

Coprolalia answered 19/8, 2012 at 15:8 Comment(2)
+1 like it! Nice one - I'd also add: if light source is far away: make the shadow more 'dispersive' ;)Visser
@Roko - Sure, why not! Edited my answer?Coprolalia
D
1

A more up-to-date answer would be to use a library like Shine.js (http://bigspaceship.github.io/shine.js/) which would handle this exact problem for you.

Detainer answered 17/12, 2017 at 8:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.