Giraffes first used to have short necks. There could be two theories that can explain why giraffes have longer necks now.
There was competition between giraffes and many other animals for foods on the ground, like shrubs. Giraffes then had to reach for higher foods that these animals could not reach, in order to survive. This resulted in their necks getting longer.
Also, something might have caused the low lying shrubs to die out. Giraffes then had to get their food from the lowest leaves on trees. Their necks gradually grew longer. This heritable trait was passed onto their offspring.
Result of Natural Selection (Time)
Then there was a variation in sizes of necks between giraffes.
Only the giraffes with longer necks survived because they could reach their food, whereas giraffes with short necks couldn't.
Giraffes with longer necks reproduced and their long neck traits were passed onto their offspring. This is why giraffes with shorter necks either died out, or developed into the giraffes with longer necks we see today.