Better Effects for images using CSS filter [code snippet]

Better Effects for images using CSS filter [code snippet]

It is very common for developers to use the good old box-shadow when they want to create a hover effect. However if your image is not square and has a transparent background, like this doggy below. It will look all sorts of strange.

In the example above, we use the standard box-shadow and as you can see it makes the dog look as if it is locked inside a box :( Poor dog.

.img-1:hover{
  box-shadow: 14px 10px green
}

But there is a better way to do this and we can free that puppy and that is to use the CSS filter attribute

Just updating to use this attribute instead with the following code results in the puppy being free and it now has a smooth shadow.

.img-1:hover{
  filter: drop-shadow(14px 10px 8px green)
}

If you want to see this code in action here is a codepen for you.

But why stop there!!!

what else can the filter attribute do apart from drop-shadow? Let's take a look.

Blur

Applies a Gaussian blur to the input image.

.img-1{
  filter: blur(2px)
}

Brightness

Applies a linear multiplier to the input image

.img-2{
  filter: brightness(2);
}

Contrast

Adjusts the contrast of the input image.

.img-1{
  filter: contrast(200%)
}

Grayscale

Converts the image to grayscale.

.img-2{
  filter: grayscale(25%);
}

.img-3{
  filter: grayscale(80%);
}

.img-4{
  filter: grayscale(100%);
}

Hue-rotation

Applies a hue rotation.

.img-2{
filter: hue-rotate(90deg);
}

.img-3{
filter: hue-rotate(130deg);
}

.img-4{
filter: hue-rotate(-90deg);
}

Invert

Inverts the samples in the input image

.img-2{
  filter: invert(100%);
}

Opacity

Applies transparency to a source image

.img-2{
  filter: opacity(50%);
}

Saturate

Saturates the image

.img-2{
  filter: saturate(200%);
}

.img-3{
  filter: saturate(300%);
}

.img-4{
  filter: saturate(400%);
}

Sepia

Converts the image to sepia

.img-2{
  filter: sepia(100%);
}

Now you have all the filter tools to start combining and making cool hover effects and image manipulations. Why not try making a quick app where a user uploads a photo and can click buttons to apply these filters and save them.

Puppy Image Source : https://www.vecteezy.com/png/27291152-cute-puppy-dog-no-background-image-applicable-to-any-context-perfect-for-print-on-demand-merchandise

Subscribe to Making sense of the world around me, one blog post at a time

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe