Answer: If the graves are separated from the mosque and the mosque was not put up for their sake—rather it was erected solely for prayer—while the cemetery occupies its own, detached location; if neither site was deliberately placed next to the other and a clear barrier exists between them, then there is no objection to praying in the mosque. Such a mosque was not established upon graves, even though the cemetery may be close by.
However, if the mosque has been built over graves, praying in it is unlawful and the prayer is invalid, because the Prophet (peace and blessings be upon him) forbade praying at graves and forbade building mosques on top of them. He stressed this prohibition and cursed those who do it.
This is because it constitutes a means that leads to shirk (associationism) with Allah, and because it resembles the practice of Christians and other polytheists.
Consequently, constructing mosques over graves is one of the matters prohibited by Islamic law, and the Messenger (peace and blessings be upon him) cursed whoever does so. The same applies to praying at graves even when no mosque has been built over them; should a mosque be erected on them, the prohibition is even more severe. In any case, praying at graves—whether or not a mosque stands over them—is forbidden, for the Prophet (peace and blessings be upon him) forbade praying at graves or in the direction of graves, as this is one of the avenues that lead to shirk.
As for a roadway passing through the middle of a cemetery: if the road is clearly defined and the cemetery lies on either side, there is nothing wrong with it, because the route does not traverse the graves themselves; it is a separate path, set apart from the burial sites. Even if it runs between two cemeteries, there is no harm in that, like a street situated between two graveyards. Nevertheless, it is advisable to place barriers or walls around the graves to protect them from the harm of pedestrians and passers-by, thus separating them from the roadway.