Gift-Claim Text Contrast Checker: Calculate Before Rounding

Copy a deterministic two-color checker, run boundary fixtures and preserve raw contrast values for real gift-claim interface states.

Giftpack

Giftpack

• 12 min read

The brand team approves a pale gray redemption confirmation. In the review screen, its contrast result appears as 4.5 after rounding to one decimal place. A designer is about to clear the color when an engineer checks the underlying value: about 4.478. The recipient still needs to read that confirmation, and formatting the report has changed the apparent decision without changing the text.

Two interface color swatches beside a measuring desk with simple wooden tools.
The unrounded ratio decides the known color pair; the rest of the recipient flow still needs review.

Test gift-claim text with the full calculated ratio before formatting the result. The method below accepts a known foreground, a known background and an explicit threshold. It supplies copyable code and boundary fixtures for that arithmetic. The design owner still needs to choose the applicable criterion, verify the rendered colors and complete the rest of the page’s accessibility review.

Set the criterion before calculating

describes the text contrast criterion and says not to round a computed ratio when comparing it with the threshold. Ordinary text generally uses 4.5:1; qualifying large text uses 3:1. A higher project target may also be selected. These are text requirements with defined exceptions, rather than a universal rating for an entire interface.

The , dated December 12, 2024 in the current retrieved document, is the standards reference behind the supporting explanation. provides US federal practice context and distinguishes text and non-text issues. All three sources were checked November 23, 2026. The federal guidance does not establish that every private company is legally subject to Section 508.

Choose the threshold with the accessibility owner before judging the pair. A field called “large” in a design system does not prove the rendered text qualifies for a lower threshold. Likewise, a designer should not select 3 solely because the proposed color fails 4.5. The checker accepts the chosen number; it cannot determine the text’s classification from a color string.

Give the test a specific subject. “Choose my gift label, default state, theme revision six” can be tied to an actual pair. “Brand palette approved” cannot tell the reviewer which color sits beneath which text. A palette may contain useful colors that fail when combined in a particular state. Approving the individual swatches is different from approving every possible pairing.

The opening confirmation is meaningful information. It should not be classified as decorative merely to avoid a failed comparison. Similarly, a live claim instruction does not become a logo because it uses a brand font. Document a real exception only when its definition applies, and keep essential recipient instructions in the tested inventory.


Use a deliberately narrow input contract

The checker takes exactly two opaque six-digit hexadecimal sRGB colors and an explicit threshold of 3, 4.5 or 7. Requiring the full format makes the method easy to inspect. It rejects shorthand, transparency and unrecognized strings rather than guessing what the developer intended. It also requires a supplied background instead of assuming the page is white.

An input such as #777777 means three eight-bit channels with the same value. The checker converts each channel to a number from zero to one, linearizes it and combines the channels into relative luminance. It uses the current sRGB breakpoint of 0.04045. Keep that method version with the test results so a future implementation change is distinguishable from a theme change.

The formula uses luminance values rather than simply comparing the hexadecimal numbers or averaging the raw channel values. The lighter luminance receives 0.05 and is divided by the darker luminance plus 0.05. The ratio is dimensionless. Reversing foreground and background produces the same arithmetic ratio, although those two interface designs can have other differences that still need review.

The numeric method is deterministic for supported inputs. Its narrow contract is a feature: a photograph, translucent overlay or gradient requires a different evaluation of the actual background beneath the text. Returning an error for an unsupported input is more useful than returning a confident ratio for a background the function has not modeled.

Here is the complete calculation. It runs in a JavaScript environment and does not need a network service or a vendor account. Keep the function with the fixtures below when integrating it into a project. Do not change the returned decision to use a rounded display string.

function contrast(fg, bg, threshold = 4.5) {
  if (![3, 4.5, 7].includes(threshold)) throw Error("threshold");
  function luminance(hex) {
    if (typeof hex !== "string" || !/^#[0-9a-fA-F]{6}$/.test(hex)) {
      throw Error("opaque #RRGGBB required");
    }
    const rgb = [1, 3, 5]
      .map(i => parseInt(hex.slice(i, i + 2), 16) / 255)
      .map(v => v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4);
    return rgb[0] * 0.2126 + rgb[1] * 0.7152 + rgb[2] * 0.0722;
  }
  const a = luminance(fg), b = luminance(bg);
  const ratio = (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
  return { ratio, threshold, passes: ratio >= threshold };
}

Store the foreground, background, threshold, raw ratio and Boolean result together. A human report may display fewer digits, but its pass or fail must come from the returned Boolean. If the interface shows a rounded boundary value, also provide enough detail to make a failure understandable. Otherwise a reviewer may see “4.5, fail” and assume the software is broken.


Run boundary fixtures before trusting a report

The table gives approximate decimal results from the stated method. The decision uses the full calculated number, not the displayed approximation. Test these known pairs before running a real theme so the implementation’s basic behavior is visible.

Foreground and backgroundRatio, approximatelySelected thresholdExpected decision
#000000 and #FFFFFF214.5Pass
#FFFFFF and #FFFFFF14.5Fail
#777777 and #FFFFFF4.4780894535772154.5Fail, even when a one-decimal display says 4.5
#767676 and #FFFFFF4.5422249596052534.5Pass for this pair and criterion
#888888 and #FFFFFF3.54488621529940053, then 4.5Pass at 3; fail at 4.5
#005A9C and #FFFFFF7.1367259467Pass for the opaque pair

Also verify that reversed pairs have the same ratio, identical colors return one, and black against white returns 21. Those checks catch channel parsing or numerator mistakes. The transition from #777777 to #767676 is especially useful because both values are close to the ordinary-text threshold while requiring different decisions.

The following assertions exercise the boundary and rejection behavior. Approximate numeric checks use a tolerance only to compare expected floating-point output in a test. That tolerance must never be added to the production threshold to rescue a failing pair.

function near(actual, expected) {
  if (Math.abs(actual - expected) > 1e-12) throw Error("numeric fixture");
}
near(contrast("#000000", "#FFFFFF").ratio, 21);
near(contrast("#FFFFFF", "#FFFFFF").ratio, 1);
near(contrast("#777777", "#FFFFFF").ratio, 4.478089453577215);
near(contrast("#767676", "#FFFFFF").ratio, 4.542224959605253);
if (contrast("#777777", "#FFFFFF").passes) throw Error("rounded pass");
if (!contrast("#767676", "#FFFFFF").passes) throw Error("boundary fail");
near(contrast("#FFFFFF", "#777777").ratio,
     contrast("#777777", "#FFFFFF").ratio);
for (const args of [
  ["#FFF", "#FFFFFF"], ["transparent", "#FFFFFF"],
  ["rgba(0,0,0,.5)", "#FFFFFF"], ["#000000", undefined],
  [null, "#FFFFFF"], ["#000000", "#FFFFFF", 4.49]
]) {
  let rejected = false;
  try { contrast(...args); } catch { rejected = true; }
  if (!rejected) throw Error("invalid input accepted");
}

A rejected value should remain an unresolved test, not become an automatic pass or a zero-filled ratio. Keep the actual input and error reason in the report. If a theme export supplies a color with alpha, the next action is to identify the actual rendered pair or use a method that models compositing; removing the alpha characters changes the question.


Worked decision: a rounded number nearly clears a confirmation

Assume the normal-size confirmation uses #777777 on an opaque #FFFFFF background and the selected criterion is 4.5. The function returns approximately 4.478089453577215. Subtracting that value from 4.5 leaves about 0.021910546422785 below the threshold. A one-decimal formatter may display 4.5, but the underlying comparison remains false.

The reviewer holds that pair. The action is to change the actual foreground token, not manually edit the report or lower the criterion without justification. A proposed replacement of #767676 produces approximately 4.542224959605253 against the same white. Its margin above 4.5 is about 0.042224959605253. That clears this arithmetic test for the stated pair; it does not certify the page.

Update the real confirmation token and inspect the computed foreground and background in the implemented state. If the design tool changed while the application still uses the old variable, the new calculation has not repaired the recipient surface. Record the component, theme revision, state and exact pair from the implementation alongside the raw result.

Then check the other meaningful states that share or override the token. Assume the claim flow has a default instruction, a hover label, a focused label and a redemption confirmation. Four states require four recorded pair checks, even if some reuse the same colors. If three are confirmed and one is unknown, report three confirmed states and one unresolved state rather than “the button passes.”

If an override puts the hover label back to #777777 on white, repair that override and rerun the affected states. A successful default-state test cannot stand in for a different style rule. If the confirmation background is also changing, evaluate the new pair together; retaining the improved foreground alone does not preserve the old ratio.

Acceptance is the exact implemented version, chosen criterion, unrounded ratio and observed state for each required pair. The original one-decimal screenshot remains useful as the trigger for investigation, but it is not the release evidence. The opening near-miss is resolved when the actual token and its relevant states are retested, rather than when the report’s formatting is made more reassuring.


Worked decision: a correct ratio describes the wrong background

Assume a gift-claim label uses #005A9C on opaque white and the project selects a threshold of 7 for that label. The method yields approximately 7.136725946, so the stated pair clears the selected comparison. The margin is about 0.1367 above 7. The test record correctly describes a blue foreground on white in that specific version.

A later marketing revision places the label over a photograph. Reusing the old result would answer the wrong question because white is no longer the verified background beneath every part of the text. The earlier ratio remains correct for its inputs; its applicability to the new state has ended. A change log should show that distinction instead of calling the calculator inconsistent.

The simplest supported repair for this checker is an opaque white panel behind the text, with the implemented pair verified again. The design owner can choose that route and retain the reproducible pair. If the intended design keeps the photograph, use an appropriate evaluation of the actual background under the text, including the least favorable relevant area and any compositing. The two-color function intentionally cannot accept an image.

Do not sample one convenient light pixel and label the whole photograph white. Responsive cropping, different recipient content or an overlay can change what lies beneath the words. Identify the supported design states and the method appropriate to them. If the background cannot be bounded reliably, return the design for revision rather than assigning an arbitrary hexadecimal average.

Acceptance for the opaque-panel route is the implemented panel, text color, state and repeated result under the chosen criterion. Acceptance for a photographic route needs its own reproducible background evaluation beyond this checker. Neither route ends the broader review: keyboard operation, focus, zoom, reading order and status communication remain with the relevant design and accessibility owners.

This decision shows why a stored ratio needs a version and a subject. A mathematically correct result is not evergreen evidence for a component whose background has changed. Keep the old result as history, attach the replacement evidence to the current implementation and mark unresolved states explicitly until the actual design has been checked.


Inventory states and preserve the limits of the test

Create the state list from the recipient task. Include text that explains selection, validates an entry, reports an error and confirms redemption. Ask which states a recipient can actually encounter with keyboard or pointer interaction. A static design screen may omit a message that appears only after submission, which can be essential even though it occupies little space.

For each state, retain the exact pair and threshold rationale. A component can use a shared brand token in one state and a local override in another. Test the implemented pair rather than assuming the token name proves its value. When a token changes, search for its actual uses and identify the affected states before treating a single fixture result as coverage for the whole flow.

Keep information conveyed by color separate from the ratio calculation. A red outline may contrast sufficiently yet still leave a recipient unsure what went wrong if color is the only signal. The federal color-usage guidance is useful context for that broader review. Include text or another appropriate cue where needed; the function does not inspect meaning or generate an accessible error message.

Non-text contrast is also outside this function’s decision. A focus indicator or control boundary may need a different comparison and criterion. Do not feed every interface color into the text checker and describe the results as a complete conformance assessment. Assign those reviews explicitly so a narrow successful calculation does not make other requirements disappear from the release checklist.

The method also does not judge font readability, language clarity or whether the recipient can complete the claim. A design can pass a color comparison while using confusing instructions or an inaccessible interaction. Preserve the useful precision of the test by naming exactly what it supports. The outcome is evidence for known text-color pairs, followed by the remaining reviews needed for the actual surface.


Keep the implementation and report reviewable

When adapting the code, preserve its rejection behavior and full-value comparison. Add a fixture before changing accepted input formats. A future requirement for shorthand hexadecimal values may be reasonable, but it should be parsed deliberately and tested rather than slipping in through a permissive conversion. A future alpha-color feature needs compositing inputs and a revised method contract.

Separate display formatting from decision logic in the code and the user interface. A report might show “4.4781 against 4.5: fail” while retaining the full stored number. That gives the reviewer enough context without exposing a long decimal everywhere. Never parse the formatted string back into the decision, because doing so reintroduces the rounding error the checker was designed to avoid.

Retain a compact record of the implementation version, source method, fixture output, component version and reviewer decision. If two tools disagree, compare their inputs, color spaces, breakpoint and rounding behavior before trusting the more favorable result. An unresolved discrepancy is a reason to inspect the method, not permission to select whichever report says pass.

A useful failure record names the repair owner as well as the colors. If a shared token causes the failure, the design-system owner may need to change it and inspect dependent components. If only one confirmation has an override, the application owner may repair that state locally. Avoid changing a global token solely to clear one pair without reviewing its other uses. The same foreground can appear over several backgrounds, so a darker replacement may solve one comparison while leaving another unresolved.

Test the reporting boundary as a separate behavior. Feed the failing gray fixture through the same formatter used in the release screen and confirm that it still shows a failure. Then feed the passing neighboring gray through it and confirm the result remains a pass. This catches a system in which the calculation is correct but a downstream report recomputes status from one-decimal text. Keep the raw numeric field available to reviewers and downstream consumers rather than publishing only the formatted label.

If the claim experience supports several themes, identify the chosen theme with every result. A white panel in the default theme does not establish the background in a dark or high-contrast configuration controlled by the application. Record what the product actually renders and evaluate supported color pairs under the same contract. User-controlled settings can also require broader review; do not ask recipients to disable their preferred settings to make a brand screenshot match the test.

For an implementation handoff, give the next owner one failing fixture, one passing boundary fixture and one current component record. That small evidence set makes the intended decision easy to reproduce. Include the rejected-input examples so an integration cannot silently substitute white for a missing background. A readable method that stops on unsupported input is easier to maintain than a report whose reassuring result depends on hidden defaults. Give the next reviewer the raw output as well, so the boundary decision can be reproduced without trusting a screenshot.

Run the method again after a theme, token, state or background change. Reuse a result only when the same pair and relevant implementation conditions still apply. This makes the test repeatable without implying that every release needs an entirely new accessibility project. The review can focus on changed evidence while preserving valid records for unaffected states.

When this check becomes an acceptance item, use the to state the recipient surfaces and responsible parties, then the to place the result in the agreed launch gates. Ask which states can actually be inspected and retained. These routes do not establish that a provider includes this checker or that a numerical result certifies the whole interface.

The inline calculator in this article is version 2026-12-04.1. Assign implementation maintenance to the front-end owner and threshold approval to the accessibility lead. Re-run the fixed cases when the parsing rules, calculation, adopted source requirements or input contract change; recheck affected screen states when their foreground, background or text classification changes. Keep each previous version and its results rather than overwriting them.


Ask Giftpack which recipient surfaces are in scope

describes recipient choice and program configuration. Its is a relevant place to confirm the actual storefront scope for a proposed program. Ask which recipient surfaces and brand changes the program can control, how those changes are reviewed and who owns the resulting implementation.

For a , bring the approved color pairs, relevant component states and the review requirements for the actual claim experience. Confirm current capabilities rather than assuming a built-in contrast checker or an automatic accessibility certification. The design and accessibility owners retain responsibility for choosing the criterion and accepting the implementation.

The practical next step is to run the fixtures, test the real confirmation pair and inspect every meaningful changed state. Keep the raw ratio and format it only after the decision. A gift claim should not clear a failed text pair because the report rounded the number upward.

Giftpack

Giftpack

• 12 min read

About Giftpack

Giftpack is the world's leading Emotional Intelligence platform for business success, serving 1,400+ companies with AI-powered relationship automation. Our intelligent infrastructure transforms how enterprises build loyalty, retain talent, and strengthen partnerships through personalized rewards and recognition. With global reach across multiple countries and seamless integrations to CRM and HRIS systems, we automate meaningful connections that drive measurable business outcomes. From employee onboarding to client retention, Giftpack helps companies build authentic relationships while achieving exceptional recipient satisfaction.

Sign up for our newsletter

Enter your email to receive the latest news and updates from Giftpack.

By clicking the subscribe button, I accept that I'll receive emails from the Giftpack Blog, and my data will be processed in accordance with Giftpack's Privacy Policy.

Honor Every Relationship with Personalization

Try for freeBook a Call
  • SOC2 logo
  • GDPR logo
  • CCPA logo
  • Vanta SOC2 logo
  • Vanta GDPR logo
  • Comodo Secure logo
  • Comodo Secure logo

©2026 All Rights Reserved. Giftpack Inc.®