Adjust the font color to match the background in a div

I am currently working on a project where I need to place text on a dynamically generated background. To ensure that the text is clear and readable, I want to determine the color of the text based on the background.

After some experimentation, I came up with the following solution:

function invert(color){
   return (color.replace('#','0x')) > (0xffffff/2) ? 'black' : 'white'
}

Using this function, I found that it returns black for red. invert('#ff0000') => black (Although white would be more suitable for red)

Do you think this approach is sufficient, or do you have any suggestions for a better method?

Answer №2

Here is a clever jQuery solution I devised on jsfiddle:

It's worth noting that with this method, the background-color value can range from rgb(50, 205, 50) to lime to #32CD32 and still function correctly.

Here is how you would implement it in your HTML:

<div id="test" style="background-color: #000000;">Can you see this text?</div>​

And for the JavaScript part:

$(document).ready(function(){
    var color = $('#test').css('background-color');
    var startIndex = color.indexOf('(') + 1;
    var lastIndex = color.indexOf(')');

    var values = color.substr(startIndex, lastIndex - startIndex).split(',');

    var r = 0;
    var g = 0;
    var b = 0;

    $(values).each(function(i) {
        if (i == 0) {
            r = 255 - values[i];
        }
        if (i == 1) {
            g = 255 - values[i];
        }
        if (i == 2) {
            b = 255 - values[i];
        }
    });

    $('#test').css('color', 'rgb(' + r + ',' + g + ',' + b + ')');
});​



UPDATE: A non-jQuery approach that doesn't support color names like lime, blue, red, etc:

function invert(color) {
    var startIndex = color.indexOf('(') + 1;
    var lastIndex = color.indexOf(')');

    var values = color.substr(startIndex, lastIndex - startIndex).split(',');

    var r = 0;
    var g = 0;
    var b = 0;

    for(i= 0; i < values.length; i++) {
        if (i == 0) {
            r = 255 - values[i];
        }
        if (i == 1) {
            g = 255 - values[i];
        }
        if (i == 2) {
            b = 255 - values[i];
        }
    }
    return 'rgb(' + r + ',' + g + ',' + b + ')';
}

Answer №3

This method is effective for all types of colors.

const luminanceValues = {red: 0.2126, green: 0.7152, blue: 0.0722};
const chosenColor = '#ffaa11'; // selected color
let redValue = parseInt(chosenColor.substring(1,3), 16);
let greenValue = parseInt(chosenColor.substring(3,5), 16);
let blueValue = parseInt(chosenColor.substring(5), 16);
let rgbArray = [redValue / 255, greenValue / 255, blueValue / 255];
for (let i = rgbArray.length; i--; )
    rgbArray[i] =
        rgbArray[i] <= 0.03928 ?
            rgbArray[i] / 12.92 :
            Math.pow(((rgbArray[i] + 0.055) / 1.055), 2.4);
let threshold = ((luminanceValues.red * rgbArray[0]) +
              (luminanceValues.green * rgbArray[1]) +
              (luminanceValues.blue * rgbArray[2]));
// if threshold is higher than 0.22, set text color to #222
// otherwise, set it to #ccc
// this ensures legible text on any hexadecimal background.

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

What is the best way to resize SVG graphics effectively?

I am in need of creating a seating chart. I have generated an SVG with the seats. <div class="seats-map"> <svg xmlns="https://www.w3.org/2000/svg" id="seats-map-svg" viewBox="0 0 1000 300"> <g data-row ...

What is the best way to insert text between the logo and menu items using bootstrap?

I've attempted several methods without much success. Here is a snippet of the code: <nav class="navbar navbar-default navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" ...

Sync user information when alterations are made on a different device

As I create a Discord clone using Next.js, I've encountered an issue where when a server is deleted, another client can still see and use the server until the page is reloaded. When testing out the official Discord web app, changes seemed to happen in ...

What is the best way to enhance the appearance of labels on my Google Maps using the Google Maps API?

I've created a map that pulls data points from a json file. I've successfully displayed an image as a marker and added a label, but I'm struggling with styling the label. How can I add style to the label without affecting the map or coordina ...

Angular CLI is not displaying CSS

I am currently using angular cli version 1.4.3, node version 6.11.3, and npm version 5.4.2. My goal is to retrieve records using angular2 and display them on localhost. I expected the output to look like this: https://i.sstatic.net/S8TVI.jpg however, the ...

Sending messages on Discord.js at one-minute intervals

Hey there, I'm currently facing an issue while trying to automate a message sending process on Discord. The specific error that keeps popping up is: bot.sendMessage is not a function I'm puzzled as to why this error occurs, so I've include ...

Unraveling Vue Async Components - Harnessing the power of emitted events to resolve

I am looking to create a Vue async component that stays in a loading state until a custom event is triggered. This means it will render a specified loading component until the event occurs. Here's an example of how I want it to work: const AsyncComp ...

"Adding page-specific scripts with the help of nunjucks and express app: A step-by-step guide

What is the most efficient way to manage scripts that are common for all pages and scripts that are specific to certain pages using nunjucks as the template engine and express 4 as the backend framework? --- site --- public |___js |___ script.js (f ...

Looking to reload a div with a captcha in a contact form without the need to refresh the entire page

I have integrated a div tag into my contact form to contain the captcha elements. If the user is unable to read the captcha image, I want to provide them with an option to refresh that specific section without reloading the entire page. I have tried variou ...

Flexible Box Model Parent with Children Having Full Height

I'm currently developing an application featuring a custom calendar that utilizes Flexbox for styling, with all the date logic being managed by React. While the calendar is working perfectly fine, I've encountered a styling issue that has me stu ...

- "Is it possible to extract values from an optional variable?"

Is there a method to access individual variables from the data returned by the reload method? let reloadProps: ReloadProps | undefined; if (useClientSide() === true) { reloadProps = reload(props.eventId); } const { isTiketAdmin, jwt, user ...

Modifying the Inactive Tab Color in Material UI

For my application, I have a specific requirement where the active tab needs to be styled in red and the inactive tab in blue. Here is how the styling is set up: newStyle: { backgroundColor: 'red', '&$selected': { b ...

Tips for incorporating the "define" function into your Mocha testing

Starting my journey with JavaScript testing, I made the decision to use Mocha. The specific modules I am looking to test are AMD/RequireJS. However, it appears that Mocha only works with CommonJS modules. Consequently, when trying to run it, I encounter t ...

Detect the "@" character through keyUp for the implementation of @mentions feature

I am currently working on implementing an @mention feature using Vue and Vanilla JS, but I am facing issues with targeting the "@" character specifically. Within my template: <trix-editor ref="trix" @keyup="listenForUser" ></trix-editor& ...

Error message in React/ Ruby on Rails: Encountered Uncaught TypeError when trying to access properties of undefined (specifically, 'id') while passing down a mapped prop

I have been grappling with this bug for the past few days and haven't found a solid solution yet. My objective is to route to an individual component, [http://localhost:4000/hris/employees/1], and display that specific 'employee' card on a ...

The CSS overflow scroller trims the excess background color

Attempting to build a website, I encountered an issue with displaying a scroll bar. Despite using the CSS property overflow: auto, I faced another problem. Let me illustrate the issue through a simple example. I have an outer div with the style overflow: ...

Configuring Google Chart LineChart settings by utilizing the series attribute

I am looking to modify the options for my line chart. However, when I define the options as shown below, the first series setting gets ignored and only the second series property is applied. var options = { title: 'Temperature Graph ( sampling ev ...

Tips for Placing a Div in a Precise Location

I'm currently working with Bootstrap and I'm attempting to replicate a layout similar to the one used by Twitter, as shown in the screenshot below. The specific part I'm struggling with is where the profile picture is located. I want to add ...

Utilizing Angular to Toggle Visibility with Button Directives

Within my main view, I have three directives that each display different sets of data. <div> <sales-view></sales-view> </div> <div> <units-view></units-view> </div> Addi ...

How can CSS grid be used to move a particular <td> element?

Currently, I am working on creating a dynamic table using CSS grid and I am looking to slightly adjust the left-most <th> and <td>. I am uncertain about how to move a specific element within a <table>. My goal is to achieve a layout simi ...