Due to natural variation due to mutations in their DNA, some giraffes in the population had longer necks. These longer necks enabled them to reach leaves higher up on the trees, which secured them a good source of food that had less inter-species and intra-species competition. Therefore in times of scarcity, they were more likely to be able to get food, and so reach reproductive age. They could then pass on their genes, and their long necks, to future generations. This continued until giraffes had such long necks that the selective advantage of having longer necks was outweighed by other factors (weight, neck muscle strength, speed, balance) etc.