Advanced Sass : online course

unique-id() function

From the Sass documentation:


Returns a unique CSS identifier. The identifier is returned as an unquoted string. The identifier returned is only guaranteed to be unique within the scope of a single Sass run.

In the real world: Simplify animation keyframes with unique-id()

So, what does unique-id() do?

You will find unique-id() in the "Miscellaneous" section of the Sass function reference, and I'm pretty sure it's one of the least used functions out there. It returns a "CSS identifier", which is just an unquoted string that never starts with a digit (that would be against the CSS spec). Instead, it always starts with the letter "u". You can use it for whatever you need a random string though.

"Unique" means that if you invoke unique-id() multiple times, you always get a different string in return. "Within the current Sass run" means that the next time your Sass code is compiled, you get different results. So: never hard-code an expected return value. Instead, if you want to use the same string multiple times, generate it only once and store it in a variable:

Play with this gist on SassMeister.