Created
January 9, 2025 17:31
-
-
Save blakek/da17b5fd95ede241f7faaf2d796f067a to your computer and use it in GitHub Desktop.
Simple CSS-in-JS helpers (e.g. a super short `transparentize`, `cover`, etc.)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { CSSObject } from "@emotion/react"; | |
/** | |
* Clamp a number between a minimum and maximum value. | |
*/ | |
export const clamp = (value: number, min: number, max: number) => | |
Math.min(Math.max(value, min), max); | |
/** | |
* Fully cover an element. Can optionally add an offset to the edges. | |
*/ | |
export const cover = (offset: number | string = 0): CSSObject => ({ | |
bottom: offset, | |
left: offset, | |
position: "absolute", | |
right: offset, | |
top: offset, | |
}); | |
/** | |
* A really small and simple utility to add transparency to a color. | |
* | |
* @param color The color to make transparent. | |
* @param _amount A number between 0 and 1 representing the amount of | |
* transparency where 0 is the color itself and 1 is fully transparent. | |
*/ | |
export function transparentize(color: string, _amount: number): string { | |
const amount = clamp(_amount, 0, 1); | |
// Asked for 0 transparency | |
if (amount === 0) { | |
return color; | |
} | |
if (amount === 1 || color === "transparent") { | |
return "transparent"; | |
} | |
return `color-mix(in srgb, ${color} ${(1 - amount) * 100}%, transparent)`; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment