If you’re wanting to add a gradient to an image I have found a lot of posts that explain how to do it with background images. This has been the go-to strategy of mine for a while but I thought it didn’t feel quite right for every case.
In order to help keep a codebase maintainable the background image solution didn’t seem like the best solution. Whenever possible I want to keep my content in the
html and the styles in the
css. I don’t feel like that is what the
background-image property is for. If an image is a part of the content and not the background, separation of concerns says to put the image in the
::after css pseudo-element
When I needed to add a gradient on an image this week I decided to get a cup of coffee* and think about it for a minute before going with the
background-image approach. The quick ponder paid off as I sat back down to try what came to mind.
TL;DR The How To
I created a CodePen but thought I’d explain some things here.
- You need to surround the
<img />tag with a
<div>. This is because presently, the CSS spec doesn’t specify how exactly the
::afterinteracts with replaced elements and the
imgis a replaced element.
- This isn’t supported before IE 10 or below. caniuse linear-gradient
- You can do a lot with that
linear-gradient. Using multiple color stops will give you a lot of flexibility.
- To adapt for different size layouts you might need to add those breakpoints in and adjust the height of the
:after: If you’re referring to content,
::should be used.
beforeare examples of content whereas
hoveraren’t content. The
::is supported above IE8 but if you need IE8 support you can’t use
linear-gradientand thus all this is for not. I understand…IE must be supported in some cases. Your pain is real.
:before: You could do this with a
afterfeels right here. If you want a gradient from the top then
beforewould be perfect. Adapt this to your needs.
* I recently joined the Portland WeWork and they have ready-made coffee. #awesome