We analyze how preferences for STEM fields moderate the effect of classroom gender composition on the math grades of girls in high school. Using data from Switzerland, we compare students who have self-selected into a STEM specialization with students who have self-selected into a language specialization. Our identification exploits the random assignment of students to classrooms after they have chosen their specialization. In contrast to the average effects found in previous studies, we find a negative effect of the proportion of female peers in the classroom on math grades for girls who have self-selected into the STEM specialization and a positive effect for girls who have self-selected into a language specialization. These results are important for policies affecting the gender composition of classrooms.