-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcreate-fluid-value.ts
More file actions
62 lines (56 loc) · 1.75 KB
/
Copy pathcreate-fluid-value.ts
File metadata and controls
62 lines (56 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
More info:
https://www.smashingmagazine.com/2022/01/modern-fluid-typography-css-clamp/
*/
const DEFAULT_MIN_SCREEN = 360;
const DEFAULT_MAX_SCREEN = 1040;
const HTML_FONT_SIZE = 16;
/**
* It returns a CSS `clamp` function string that will fluidly
* transition between a `minSize` and `maxSize` based on the screen size
* @param minSize - Defines the lower limit of your fluid value.
* @param maxSize - Defines the upper limit of your fluid value.
* @param minScreenSize - When the fluid value should stop shrinking.
* @param maxScreenSize - When the fluid value should stop growing.
* @returns A string that is a css `clamp()` function
*/
export const createFluidValue = (
minSize: number,
maxSize: number,
minScreenSize: number = DEFAULT_MIN_SCREEN,
maxScreenSize: number = DEFAULT_MAX_SCREEN,
) => {
return `clamp(${pxToRem(minSize)}, ${getPreferredValue(
minSize,
maxSize,
minScreenSize,
maxScreenSize,
)}, ${pxToRem(maxSize)})`;
};
/**
* Determines how fluid typography scales
*/
const getPreferredValue = (
minSize: number,
maxSize: number,
minScreenSize: number,
maxScreenSize: number,
) => {
const vwCalc = cleanNumber(
(100 * (maxSize - minSize)) / (maxScreenSize - minScreenSize),
);
const remCalc = cleanNumber(
(minScreenSize * maxSize - maxScreenSize * minSize) /
(minScreenSize - maxScreenSize),
);
return `${vwCalc}vw + ${pxToRem(remCalc)}`;
};
const pxToRem = (px: number | string) =>
`${cleanNumber(Number(px) / HTML_FONT_SIZE)}rem`;
/**
* It takes a number, adds a very small number to it, multiplies it by 100, rounds
* it, and then divides it by 100
* @param num - The number to be rounded.
*/
const cleanNumber = (num: number) =>
Math.round((num + Number.EPSILON) * 100) / 100;