Pure CSS Depth of Field Effect

hello and welcome to Red Stapler in
this tutorial we are going to show you how to create depth of field effect
which could be useful for creating stunning background on your website this
technique used only CSS and can be done in just a few minutes let’s check
it out so we will need two separated images First is background and another is
object that closer to your eyes in this case I will use a rifle image captured
from call of duty game next I’ll create divs for both images for the CSS first
let’s set the background image I will set the position to absolute and set the image size a little bit
larger than the viewport if we don’t do this you’ll see the white area around the
edges when we applied the blur filter also add overflow:hidden to the body to
remove the scrollbar next let’s add a rifle similar to background except we
will place them at the bottom right you will notice that I use percentage
padding-bottom instead of height this is to preserve aspect ratio if user resize
the window then we will create a hover pseudo-class for both divs to remove the
blur filter also add one second transition and this is the easiest way to do it
with pure CSS method but if it’s okay for you to add a small JavaScript then
we can capture the mouse position and adjust the depth dynamically so let’s
remove the blur filter and hover class then in a JavaScript we’ll set the
focus point for each div I’ll set the focus point of the background to 50
pixels from top and 1000 pixels for the rifle then create a new style element
and add it to the body so if you want to add any CSS in the future we can inject
them to this element then we will add mouse move event listener inside we will calculate the blur amount
from the current mouse vertical position the more distance from the focus point
the more blur amount should be applied and finally we will apply the blur
filter to the style element we just added and to make it more realistic we’ll add
a small scale transform to the background and that’s it for this tutorial hope you
guys enjoy if you love to see more development tips and tutorials don’t
forget to subscribe to our channel to stay tuned thanks for watching and see
you next time bye


Add a Comment

Your email address will not be published. Required fields are marked *