Darkening an image with CSS (In any shape)

2019-02-07 20:32发布

So I have seen quite a few ways to darken images with CSS, including ones with rounded corners, but my problem is different.

Let's say I have an .png image that looks like a little dog (just go with it, I don't have any good examples), when I place it on my page, I give it dimensions of 100 x 100.

But I can't just overlay something on it, or tint the entire image, as it will cause the background of the dog to be tinted as well, which looks ugly.

Is it possible to tint an image of arbitrary shape with CSS?

(I'm assuming you understand my point, and useless code is not necessary)

Thanks!

标签: css png tint
4条回答
来,给爷笑一个
2楼-- · 2019-02-07 21:20

Easy as

img {
  filter: brightness(50%);
}
查看更多
戒情不戒烟
3楼-- · 2019-02-07 21:20

I would make a new image of the dog's silhouette (black) and the rest the same as the original image. In the html, add a wrapper div with this silhouette as as background. Now, make the original image semi-transparent. The dog will become darker and the background of the dog will stay the same. You can do :hover tricks by setting the opacity of the original image to 100% on hover. Then the dog pops out when you mouse over him!

style

.wrapper{background-image:url(silhouette.png);} 
.original{opacity:0.7:}
.original:hover{opacity:1}

<div class="wrapper">
  <div class="img">
    <img src="original.png">
  </div>
</div>
查看更多
虎瘦雄心在
4楼-- · 2019-02-07 21:22

You could always change the opacity of the image, given the difficulty of any alternatives this might be the best approach.

CSS:

.tinted { opacity: 0.8; }

If you're interested in better browser compatability, I suggest reading this:

http://css-tricks.com/css-transparency-settings-for-all-broswers/

If you're determined enough you can get this working as far back as IE7 (who knew!)

Note: As JGonzalezD points out below, this only actually darkens the image if the background colour is generally darker than the image itself. Although this technique may still be useful if you don't specifically want to darken the image, but instead want to highlight it on hover/focus/other state for whatever reason.

查看更多
成全新的幸福
5楼-- · 2019-02-07 21:34

Webkit only solution

Quick solution, relies on the -webkit-mask-image property. -webkit-mask-image sets a mask image for an element.

There are a few gotchas with this method:

  • Obviously, only works in Webkit browsers
  • Requires an additional wrapper to apply the :after psuedo-element (IMG tags can't have :before/:after pseudo elements, grr)
  • Because there's an additional wrapper, I'm not sure how to use the attr(…) CSS function to get the IMG tag URL, so it's hard-coded into the CSS separately.

If you can look past those issues, this might be a possible solution. SVG filters will be even more flexible, and Canvas solutions will be even more flexible and have a wider range of support (SVG doesn't have Android 2.x support).

查看更多
登录 后发表回答