Part of this is that students are not a protected class under the Fair Housing Act (FHA). So an educational organization that offers housing, can say that the housing is for students only, and not offer housing to the general public. That doesn't mean the FHA doesn't apply, but what it does mean is that students can be discriminated against.
So, first a college can say that they only admit male or female students (an all-one-sex college, not many exist but they are out there). They can also state that the housing that they offer is for students only, which would limit a dormitory to all male/female occupants.
Second, a college that is mixed-gender can provide both types of housing and say that one type of housing is for males and the other females. They can limit this by only admitting X number of male students and Y number of female students (my college did this and had limited female housing, with about a 10:1 male-female admittance).
This isn't discrimination as it applies under the FHA. They aren't offering rooms to the general public (you need to be a student to get into the dorms). That means that these rooms are being assigned based on sex, but you are not denied a room based on gender (you may be denied admission, but that is another topic). For example you usually don't walk through the dorms and pick out your favorite room like you would an apartment, they are assigned.
FHA applies to students, a female student can be assigned a female dorm, and a male in a male dorm, but it is not discrimination to say that "Dorm X is all female, Dorm Y is all male". So long as the policy applies to all students equally, it is not discrimination.
So, for example an all-female school can only admit females. It can say that "only students allowed in the dorms", and because only females are students, that means that only females can live there.
Off campus housing is an entirely different matter if it is not owned or operated by the school.