An analysis of the fern vegetation on 156 plots along an elevational gradient (45-3400 m) in undisturbed forests in Costa Rica, Central America, showed a hump-shaped pattern of species richness with a maximum of up to 68 species per 400 m² at mid-elevations. This study documents the contribution of specific habitats (forest types: ridges, ravines) and niches within them (dead wood, rocks, growth zones in trees) to the local fern richness and the relation of species richness to elevation and climatic variables. Forests along ravines showed significantly higher species richness, presumably caused by high environmental humidity. The mean number of individuals of occupied niches per species increased significantly with elevation, suggesting that the niche breadth of species increased and that the differentiation of niches decreased with elevation. Both findings may explain the reduced fern species richness towards and above the upper treeline, but not at low elevations. The key factors for the decreases of species richness at the extremes of the gradient are likely to involve climatic conditions.