简体   繁体   中英

Overlaying image without affecting transparent

I want to color an image using css, but without affecting its transparent parts.

For example: if I have little brown square in an image with transparent background, i want to turn ONLY the square into another color.

I've found this guide (http://css-tricks.com/forums/discussion/10828/color-overlay-img/p1) but it affects the transparent part as well.

Thanks in advance

What you can do is place a <div> under the image at the dimensions you want to colour. This is what I would do:

<div class="image">

    <div class="colour"></div>
    <img src="[..].png" alt="Some image" />

</div>

And then the CSS:

.image{
    width: 100px; /* The image width */
    height: 100px; /* The image height */

    position: relative;
}

.image .colour{
    width: 30px; /* Width of the part you want to colour */
    height: 30px; /* Height of the part you want to colour */

    position: absolute;
    top: 35px; /* Y coordinate */
    left: 35px; /* X coordinate */
}

.image img{
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1; /* Place above the coloured part */
}

If the region is rectangular

  • Overlay another element with a bg color on top of the image.

If the region is non-rectangular

  • Swap out the image with another one at the appropriate time via CSS.
  • Overlay another image (with transparent pixels where needed) over the image.
  • Overlay a canvas or SVG image on top of the image.
  • Use canvas or SVG for the image and edit the image when needed.

I don't believe there's a general-purpose way to do this with CSS alone (without touching the HTML, or using more than 1 image file, or using canvas or SVG, or using JS or jQuery). If it's not possible to touch the HTML source code, you could modify the HTML dynamically with JS or jQuery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM