在 CSS 中如何让浏览器选择一种对比色

  • contrast-color() Function: Allows CSS to determine whether black or white should be paired with a declared color. It simplifies color contrast management. For example, color: contrast-color(purple); makes the browser set the color to either black or white based on contrast.
  • Button Styling Example: Sets button background color with a variable and text color as the contrasting black/white choice. button { background-color: var(--button-color); color: contrast-color(var(--button-color)); }. It also defines a hover color using relative color syntax.
  • Accessibility Considerations: Using contrast-color() doesn't guarantee accessible color pairs. The current Safari Technology Preview implementation uses the WCAG 2 algorithm which may not always choose the most perceptually contrasting color. For example, a medium dark blue with a contrast-color of black is less perceptually contrasting than white. The APCA (Accessible Perceptual Contrast Algorithm) may give better results.
  • Providing Enough Contrast: Use the prefers-contrast media query to offer alternative styling for those who want more contrast. Consider font size and weight in combination with color contrast. For example, for a specific shade of green, different font sizes and weights may affect contrast.
  • Beyond Black & White: The newer contrast-color() function is simplified and only chooses between black and white for now. In the future, more complex tools may be developed to support more color options. contrast-color can be used for various elements beyond just text on a color background.
  • Continue the Conversation: Learn more about APCA on its GitHub repository. Feedback on contrast-color() is welcome and can be shared with relevant web evangelists or followed on social media.
阅读 26
0 条评论