In mammals, dosage compensation of X linked genes in female cells is achieved by inactivation of one of their two X chromosomes which is randomly chosen. The earliest steps in X-chromosome inactivation (XCI), namely, the mechanism whereby cells count their X chromosomes and choose between two equivalent X chromosomes, remain mysterious. Starting from the recent discovery of X chromosome colocalization at the onset of X-chromosome inactivation, we propose a statistical mechanics model of XCI, which is investigated by computer simulations and checked against experimental data. Our model describes how a "blocking factor" complex is self-assembled and why only one is formed out of many diffusible molecules, resulting in a spontaneous symmetry breaking in the binding to two identical chromosomes. These results are used to derive a scenario of biological implications.