A Stone That's Actually a Rock
Unlike gems such as diamond or emerald, lapis lazuli isn't a single mineral but a rock: a mix of several different minerals. The main one is lazurite, an intense blue mineral that supplies almost all of the color; alongside it usually appear white calcite, which forms light-colored veins, and golden pyrite, which speckles the stone with tiny bright flecks, like a miniature starry sky.
That combination doesn't appear just anywhere. Lapis lazuli forms when limestone — that is, rock rich in calcium carbonate, the kind that makes up much of many cliffs and caves — becomes trapped next to an intrusion of magma and is subjected, over millions of years, to intense heat and pressure, in a process called contact metamorphism. It's a mineral transformation similar to the one that gives rise to other stones such as emerald, though with a completely different cast of elements: here, what matters is the presence of sulfur, which is exactly what tints lazurite that characteristic blue.
Contact metamorphism happens when an already-existing rock ends up literally pressed against a pocket of magma rising from inside the Earth. The rock doesn't need to melt: the heat and pressure from the nearby magma are enough for its minerals to reorganize over thousands or millions of years, giving rise to new minerals — like lazurite — that weren't present in the original rock.