The animals with longer necks are more likely to survive, because they can reach their food better. The tall genes are inherited to their children, of whom the one with the longest neck is most...
Natural selection. Since the leaves in the tall trees are the food of giraffes, the tallest giraffes get the most food, live the longest, and produce the most offspring. The genes for "long necks"...
Giraffes have long slender necks so that they can reach the freshest leaves that are very high up in the trees. No other animals can get to these leaves.