Cyanobacteria are photosynthetic prokaryotes that inhabit diverse aquatic and terrestrial environments. However, the evolutionary mechanisms involved in the cyanobacterial habitat adaptation remain poorly understood. Here, based on phylogenetic and comparative genomic analyses of 650 cyanobacterial genomes, we investigated the genetic basis of cyanobacterial habitat adaptation (marine, freshwater, and terrestrial). We show: (1) the expansion of gene families is a common strategy whereby terrestrial cyanobacteria cope with fluctuating environments, whereas the genomes of many marine strains have undergone contraction to adapt to nutrient-poor conditions. (2) Hundreds of genes are strongly associated with specific habitats. Genes that are differentially abundant in genomes of marine, freshwater, and terrestrial cyanobacteria were found to be involved in light sensing and absorption, chemotaxis, nutrient transporters, responses to osmotic stress, etc., indicating the importance of these genes in the survival and adaptation of organisms in specific habitats. (3) A substantial fraction of genes that facilitate the adaptation of Cyanobacteria to specific habitats are contributed by horizontal gene transfer, and such genetic exchanges are more frequent in terrestrial cyanobacteria. Collectively, our results further our understandings of the adaptations of Cyanobacteria to different environments, highlighting the importance of ecological constraints imposed by the environment in shaping the evolution of Cyanobacteria.