Giraffes with longer necks would have had higher survival because of the ability to obtain food not obtainable by other species. There was difference in neck length among individuals and it had a genetic basis. As a result of longer necked giraffes having higher fitness, alleles for longer necks would have been passed from generation to generation more than alleles for shorter necks, so over time more and more giraffes would have been born with long necks, until all had long necks, an adaptation to feeding on tall trees in their environment. Over time, because black moths survived to reproduce better than did gray moths, alleles for black color became more and more common. They occur regardless of whether or not they are adaptive.
Genes can also differ in mutation rate.
Occasionally adaptive mutations arise.