How to create a transparent background effect in CSS for image with white background

I need help with two images on my website. One is a small icon that overlaps the first image, but since the icon has a white background, it creates a white square effect when placed on top. I want to avoid displaying this white background over my other image. Is there a CSS property I can use to make the white background of my icon transparent?

Answer №1

Another option is available, but it is currently only compatible with Chrome, Firefox, and Safari browsers. If the background color of your element is white, you can utilize the CSS property:

mix-blend-mode: multiply;

To learn more about this feature, check out this link: https://developer.mozilla.org/en-US/docs/Web/CSS/mix-blend-mode

Answer №2

The Transparency Trick

mix-blend-mode may work for certain browsers, but we have experienced performance issues with Chrome without knowing the exact cause.

An innovative solution was devised by a designer in our team - creating a transparent layer that blends seamlessly with its background color when overlaid on white.

This "magical" color is achieved by adjusting each color axis based on the opacity level using the formula 255 - ( 255 - x ) / opacity. The challenge arises when setting opacity too low resulting in negative values or too high causing unwanted coloring outside white areas.
Initially, manual calculations were done using a spreadsheet to find the perfect hue through trial and error. With the adoption of Sass, a more efficient binary search method was developed as a sass function simplifying the process.

Explore this gist on sassmeister where you can pass your background color to the opacitator function in line 56 of the sass code. Utilize the generated rgba color within a div or pseudo element to overlay images.

To see a practical demonstration, refer to the working example on CodePen.

Answer №3

Since CSS doesn't offer a foolproof method to eliminate backgrounds, I want to share a JavaScript snippet that demonstrates how it can be done:

async function eraseBackground(image) {
  const bgColor = { red: 255, green: 255, blue: 255 };
  const threshold = 10;

  const imgElement = new Image();
  imgElement.src = image;
  await new Promise(resolve => imgElement.addEventListener('load', resolve));

  const canvas = document.createElement('canvas');
  canvas.width = imgElement.naturalWidth;
  canvas.height = imgElement.naturalHeight;

  const context = canvas.getContext('2d');
  context.drawImage(imgElement, 0, 0);
  const imgData = context.getImageData(0, 0, canvas.width, canvas.height);

  for (let i = 0; i < imgData.data.length; i += 4) {
    const redVal = imgData.data[i];
    const greenVal = imgData.data[i + 1];
    const blueVal = imgData.data[i + 2];
    if (Math.abs(redVal - bgColor.red) < threshold &&
      Math.abs(greenVal - bgColor.green) < threshold &&
      Math.abs(blueVal - bgColor.blue) < threshold) {
      imgData.data[i + 3] = 0;
    }
  }

  context.putImageData(imgData, 0, 0);
  return canvas.toDataURL(`image/png`);
}

Answer №4

Not quite there yet...

We're on the brink of it becoming possible, so take a look at this intriguing article on CSS Filters, an experimental CSS feature that's making some cool client-side advancements.

Learn more about CSS Filters

Answer №5

To contain your image, create a specific container element. Next, apply the following CSS to the container:

overflow:hidden; height: (adjust based on image size); width:100%;

I trust this information will be of assistance. :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with XFBML Like Buttons failing to load when generating numerous posts dynamically on a single page

On my webpage containing multiple posts, I am attempting to insert a Facebook LIKE button for each post. Utilizing XFBML code, I am trying to populate like buttons under every individual post with a unique URL, corresponding to the post URL. Here is the c ...

Utilizing HTML5 Video Autoplay with AngularJS ng-show: A Comprehensive Guide

How can I implement a video using the HTML5 video tag with autoplay in an AngularJS web application? I attempted to use the following code: <video ng-show="condition" autoplay ng-src="{{video.src}}"></video> Upon loading the web application, ...

Designing templates for websites and applications using node.js

Simplified Question: As I delve into improving my skills with node.js, I'm exploring the concept of templating. How would using node to serve one HTML file and loading page-specific information through AJAX/sockets impact performance and design princ ...

"Effortlessly add an image to your page and watch it appear instantly without the need

One of the features on my website is a button that enables users to select an image, as shown in the code snippet below: <div id="fileUpload"> <form id="joinPhotoUploadForm" method="POST" enctype="multipart/form-data"> ...

Using FastCGI in C with fcgi_stdio.h for handling HTML5 and UTF8

Here is a code snippet that has been working well for me: #include "fcgi_stdio.h" int main(void) { while(FCGI_Accept() >= 0) { //Simple FastCGI Example Web-page printf("Content-type: text/html\r\n" "\r\n" ...

The art of organizing information: Tables and data management

Looking for a solution with a table: <table> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> </tr> </table> Trying to format the cells to display as: 1 2 3 4 ...

Designing personalized sass components

Seeking advice on developing a custom CSS unit that can be utilized in Sass with Node.js. Is there a tutorial available for creating a Sass plugin specifically for this purpose? For instance, I am looking to establish a unit called "dpx" which functions as ...

Ways to showcase a div exclusively on UC mini browser

I'm looking for help to create a script that will only display a div with the class "info-box" in UC Mini browser. This div should be hidden in all other browsers. Can someone assist me with this? <!doctype html> <html> <head> <m ...

I recently discovered how to modify the video source (src) within an html5 source tag, but I am encountering varied outcomes when using it within a function or with inline javascript

When attempting to change the src of a video tag using Javascript, I encountered an issue. The code works fine when placed inline, but as soon as I try to include it within a function or in the "onclick" event of a button tag, nothing happens. There are no ...

jQuery Slider Showing Incorrect Images

My jQuery slider is acting strangely. It hides the first image, shows the second one, but then just repeats the cycle by showing the first image again instead of loading the third one. I'm puzzled about what could be causing this issue in my code. Do ...

The drag-and-drop feature for uploading files is not functioning properly

After following the JavaScript drag and drop script tutorial mentioned here and using the PHP upload script provided here, I made modifications to the XHR request to upload.php in the JS code. The progress now reaches 100%, but the uploaded image does not ...

How can I adjust the size of the renderer in Three.js to fit the screen?

Encountering issues with the code snippet below: //WebGL renderer renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); //TODO: set optimal size document.body.appendChild(renderer ...

The problem of a static click function not working when clicked on a link. What is the solution for this

Details I am currently using a flickity slideshow that automatically goes to the next picture on a click. Within the slideshow, I have placed a button with text and a link to an external website (e.g. ). My Problem: When I click on the link, my slidesho ...

The calc() function in LESS is malfunctioning and causing complications

My less file contains the following calculation: height: calc((100vh - 60px) + ((100vw / 9) * 3)); However, the result is not what I expected. According to my chrome devtools, the result is: height: calc(73.33333333vh); In my viewport, it should be aroun ...

Enhancing User Interaction with Bootstrap Input Forms

Struggling with a CSS and Bootstrap issue, I am unable to find a solution. The problem I am facing is that the content in a div form is not responsive within its parent div. It always extends beyond the parent div and does not adjust its size when the scre ...

Embed a YouTube video within the product image gallery

Having trouble incorporating a YouTube video into my Product Image Gallery. Currently, the main product photo is a large image with thumbnails that change it. You can see an example on my website here. Whenever I attempt to add a video using the code below ...

Tips for altering the color of a specific row in JQuery by targeting its unique id

I've been struggling to accomplish a simple task using Jquery and CSS, but I seem to be stuck. My issue involves making an ajax request to update a PostgreSQL table and retrieve an id in return. This id corresponds to the id of a row in a previously ...

Detecting changes in checkbox states

In my current scenario, I have a section of the screen that can be shown or hidden depending on whether a checkbox is checked. The user can change the state of the checkbox manually or programmatically. The challenge lies in detecting this change and upda ...

Changing the positions of objects on a resized HTML Canvas

I am currently developing a tool that allows users to draw bounding boxes on images using the Canvas and Angular. Everything was working smoothly until I encountered an issue with zooming in on the canvas causing complications when trying to draw bounding ...

Animating colors with jQuery and shifting SVG shapes to create dynamic and

I am currently working on an svg animation that involves changing the color of the svg to a different color, creating a running light effect. Rather than fading the fill color of the entire svg as commonly seen in examples, I aim to achieve a dynamic trans ...