The classic explanation is simple:
Giraffes evolved long necks so they could reach leaves other animals could not.
That is probably part of the story.
It is not the whole story.
Long necks help with feeding
Giraffes can reach foliage high in trees.
That gives them access to food beyond the reach of many competing herbivores.
During periods when food is scarce, that extra reach can matter.
Male giraffes use their necks in competition
Male giraffes fight by swinging their necks and heads at one another.
This behavior is called necking.
A larger, stronger neck can provide an advantage in those contests.
That means sexual selection may also have helped shape neck length.
Which explanation is correct?
Possibly both.
Evolution often reflects several pressures acting at the same time.
A long neck can help with feeding and with competition for mates.
There is no rule requiring one anatomical feature to have one evolutionary explanation.
Why are giraffe legs long too?
The entire body is built around height.
Long legs raise the shoulders and chest.
The long neck extends that reach further.
The result is an animal specialized for browsing high vegetation.
Does the long neck create problems?
Absolutely.
Blood has to travel a long distance between the heart and brain.
Giraffes have specialized cardiovascular adaptations to manage that pressure.
Body design is always a package of advantages and tradeoffs.
How is this like other animal features?
Just as animal tails can serve several jobs, a giraffe neck is useful in more than one context.
Evolution can build one structure and then use it several ways.
Reaching high leaves is part of the story.
So is using the neck as a weapon.
And that’s the short explanation.
Related explanations: Why do animals have tails?, Why do elephants have big ears?, and Why do zebras have stripes?