Host–pathogen interactions are of particular interest in studies of the interplay between population dynamics and natural selection. The major histocompatibility complex (MHC) genes of demographically fluctuating species are highly suitable markers for such studies, because they are involved in initiating the immune response against pathogens and display a high level of adaptive genetic variation. We investigated whether two MHC class II genes (DQA1, DRB) were subjected to contemporary selection during increases in the density of fossorial water vole (Arvicola terrestris) populations, by comparing the neutral genetic structure of seven populations with that estimated from MHC genes. Tests for heterozygosity excess indicated that DQA1 was subject to intense balancing selection. No such selection operated on neutral markers. This pattern of selection became more marked with increasing abundance. In the low-abundance phase, when populations were geographically isolated, both overall differentiation and isolation-by-distance were more marked for MHC genes than for neutral markers. Model-based simulations identified DQA1 as an outlier (i.e. under selection) in a single population, suggesting the action of local selection in fragmented populations. The differences between MHC and neutral markers gradually disappeared with increasing effective migration between sites. In the high-abundance year, DQA1 displayed significantly lower levels of overall differentiation than the neutral markers. This gene therefore displayed stronger homogenization than observed under drift and migration alone. The observed signs of selection were much weaker for DRB. Spatial and temporal fluctuations in parasite pressure and locus-specific selection are probably the most plausible mechanisms underlying the observed changes in selection pattern during the demographic cycle.