简体   繁体   中英

CSS / SCSS - Closest Value To

Maybe it's a dumb question, but there is a way to get closest value to target?

Something as writing

closest(58px, 6.4vh, 2vw)

and between 6.4vh and 2vw retrieve the closest to 58px

There isn't any runtime CSS functions for something quite like that. The most similar functions available at the moment are things like min , max and clamp .

However, this effect can be achieved using javascript to find the closest of each value to your target value and set a CSS variable so you can use that value where needed:

 const updateFontSize = (closestTo = 58) => { // Create an array of sizes with their CSS value and the current calculated value. const sizes = [ { size: '6.4vh', value: window.innerHeight * 0.064, }, { size: '2vw', value: window.innerWidth * 0.02, }, ] // Calculate the delta from 58.map((size) => ({...size, delta: Math.abs(closestTo - size.value), })) // Order by delta ascending.sort((a, b) => (a.delta - b.delta)); // Set the font size value to the nearest option document.documentElement.style.setProperty('--closest', sizes[0].size); }; // Trigger immediately and on window resize updateFontSize(58); window.addEventListener('resize', () => updateFontSize(58));
 :root { --closest: 58px; } body { font-size: var(--closest); }
 Lorem ipsum

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM