First of all, it should be clear that children are gifts from Almighty Allah. We should thank Him for His gift and accept it with satisfaction, contentment and pleasure whether it is a male or a female.
There is nothing wrong to use a fetal ultrasound to know the sex of a fetus, since it does not change or alter the will of Almighty Allah and it is only a matter related to the relative unseen and not that which is absolute.
Responding to this issue,Dr. Hatem al-Haj stated:
There are two different types of the unseen, absolute and relative. The absolute unseen belongs only to Almighty Allah, such as knowledge of the future that He did not disclose to any of His creation. While the relative unseen is like what is taking place in a different country at this time, but we do not know. It is part of the unseen because of our limited capacities and lack of encompassing knowledge, but it is not part of the absolute unseen.
The sex of the fetus in the womb is part of the relative knowledge of the unseen that is kept from some of Almighty Allah’s creation and disclosed to others. It is not in the latter stages of absolute knowledge of the unseen that belongs only to Him.
The reason why the question is asked – I think – and some Muslims may hesitate about this issue, is the following verse:
Almighty Allah says, (Verily, Allah! With Him (Alone) is the knowledge of the Hour, He sends down the rain, and knows that which is in the wombs. No person knows what he will earn tomorrow, and no person knows in what land he will die. Verily, Allah is All Knower, All Aware (of things).) (Luqman 31: 34)
That which is in the wombs here does not apply to the sex of the fetus, even though the sex may be at some earlier stage of the knowledge of the absolute unseen. It refers to everything about this creature and its future.
The proof of this is that we were told that there is an angel who knows the sex of the fetus. The Prophet (peace and blessings be upon him) said, “After the nutfah [drop (of semen)] is in the womb for forty or forty five nights, the angel enters and says: My Lord, will he be good or evil? Both will be written. Then he says, My Lord, would he be male or female? Both will be written. In addition, his deeds, actions, death and livelihood will be recorded. Then his document of destiny is rolled and there shall be no addition to it or subtraction from it.” (Muslim)
Since the angel knows the sex, it is not part of the absolute knowledge of the unseen from which all creatures are barred. Based on this, the earlier scholars did not reprimand physicians who attempted, through their rather primitive means, to guess the sex of a fetus.
Given the above, there is no harm in trying to know the sex of the baby before its birth through fetal ultrasound.