当你的网站使用了多个主题,比如 light/dark。当用户选择一段文本,常常会出现一个主题没问题,另一个主题颜色怪怪的。是因为选择区域的主题通常没有变化,导致与当前主题不配合。
下面四种方法可解决这个问题:
The problem occurs because most browsers use default system colors for text selection, which might not match your theme’s color scheme.
Here are a few ways to fix this in DaisyUI:
Method 1: CSS Custom Properties (Recommended)
Add custom CSS for text selection in your global styles:
/* Custom text selection colors */
::selection {background-color: hsl(var(--p) / 0.3); /* Using primary color with opacity */color: hsl(var(--pc)); /* Primary content color */
}::-moz-selection {background-color: hsl(var(--p) / 0.3);color: hsl(var(--pc));
}/* Dark theme specific selection */
[data-theme="dark"] ::selection {background-color: hsl(var(--s) / 0.5); /* Secondary color for dark theme */color: hsl(var(--sc));
}[data-theme="dark"] ::-moz-selection {background-color: hsl(var(--s) / 0.5);color: hsl(var(--sc));
}
Method 2: Using DaisyUI’s CSS Variables
DaisyUI provides CSS variables you can leverage:
::selection {background-color: var(--fallback-bc,oklch(var(--bc)/0.2));color: var(--fallback-b1,oklch(var(--b1)));
}[data-theme="dark"] ::selection {background-color: var(--fallback-p,oklch(var(--p)/0.3));color: var(--fallback-pc,oklch(var(--pc)));
}
Method 3: Direct Color Values
If you prefer specific colors:
::selection {background-color: #3b82f6; /* blue-500 */color: white;
}[data-theme="dark"] ::selection {background-color: #60a5fa; /* blue-400 */color: #1f2937; /* gray-800 */
}
Method 4: Using Tailwind’s @apply (if using Tailwind)
@layer utilities {.selection-light {@apply selection:bg-primary selection:bg-opacity-30 selection:text-primary-content;}.selection-dark {@apply selection:bg-secondary selection:bg-opacity-50 selection:text-secondary-content;}
}/* Apply based on theme */
[data-theme="light"] {@apply selection-light;
}[data-theme="dark"] {@apply selection-dark;
}
Complete Example with DaisyUI
<!DOCTYPE html>
<html data-theme="light">
<head><style>/* Custom text selection */::selection {background-color: hsl(var(--p) / 0.3);color: hsl(var(--pc));}::-moz-selection {background-color: hsl(var(--p) / 0.3);color: hsl(var(--pc));}[data-theme="dark"] ::selection {background-color: hsl(var(--s) / 0.5);color: hsl(var(--sc));}[data-theme="dark"] ::-moz-selection {background-color: hsl(var(--s) / 0.5);color: hsl(var(--sc));}</style>
</head>
<body><!-- Your content -->
</body>
</html>
The first method using DaisyUI’s CSS variables is recommended because it maintains consistency with your theme’s color scheme and automatically adapts if you change your theme’s primary/secondary colors.
Choose the method that best fits your project’s setup and preferences!