In the first place, we would like to make it clear that Islam is the religion of pure monotheism. It fights every hint of shirk (associating others with Allah). It tries its best to keep the `aqeedah (creed and inner belief) intact.
Sheikh `Atiyyah Saqr, former Head of Al-Azhar Fatwa Committee, states that: “Al-Bukhari and Muslim both narrated that the Prophet (peace and blessings be upon him) said, “May Allah destroy Jews! They used the graves of their prophets as mosques.” Muslim also reported that, five days before his death, the Prophet (peace and blessings be upon him) said: “Those who were before you used the graves of their prophets and saints as mosques. So, do not use graves as places for offering Prayer.”
Scholars discussed and commented on these Hadiths. Some scholars say that the blame is given in cases where the mosques are built over graves. They state that there is nothing wrong, however, if a mosque is built and then a tomb is structured beside it (as when it is the tomb of the person who built the mosque and the like). Al-`Iraqi holds the view that there is no difference between both cases. If a mosque is built for the purpose of burying someone in it, then this is included in the blame. It is even haram (prohibited) to bury anyone in the mosque, even if a person asked for this to be done for him/her after his/her death.
Some scholars said that the texts show blame for the one who does this. This blame may indicate tahrim (impermissibility) or karahah (reprehensibility). If the latter is held, then Prayer offered in a place where a tomb is built will be valid but reprehensible.
Those who hold the view that it is valid but reprehensible also hold different views. Some say that there is no difference if the tomb is in front, behind, on the right hand side or the left hand side. However, some others say that it is reprehensible only if the tomb is in front of the person offering Prayer.
The three Imams (i.e. Abu Hanifah, Malik, Ash-Shafi`i) hold the view that the Prayer is valid and not reprehensible unless the tomb is in front of the person, in which case it is still valid but reprehensible.
Imam Ahmad ibn Hanbal holds the view that it is totally prohibited to offer Prayer in such places and, if done, the Prayer is invalid. All these arguments are discussing the issue in which the tomb is inside the mosque. If the tomb is separated from the mosque and people offer their Prayer in the mosque or parts other than where the tomb is situated, then offering Prayer is permissible without any reprehensibility or prohibition. I choose the view that if the person offers Prayer as a token of honouring the tomb or glorifying it, then the Prayer is invalid and rejected and performing it is prohibited regardless of the place of the tomb. If there is no intention for anything like this, then it is only reprehensible, though valid, if the tomb is in front of the person. If the tomb is at any other direction, then there is no reprehensibility.”