Mary and Joseph were betrothed to each other at the time of Christ's birth. They had not yet consummated, however, their relationship. The Bible says the following in this regard.
And the birth of Jesus Christ was as follows: Now His mother Mary had been betrothed to Joseph; but before they came together (had sex), she was found to be with child of the Holy Spirit (Matthew 1:18 - 19, HBFV throughout).
In Biblical times, a betrothal like the one between Joseph and Mary was considered the same as being married and was a binding agreement between a man and a woman. It was usually accompanied by a partial payment of the full "bride price" paid by the groom (or groom's family) to the bride's father as compensation for the loss of his daughter to marriage
And Jacob loved Rachel, and said, "I will serve you seven years for Rachel your younger daughter." And Laban said, "It is better that I give her to you than I should give her to another man. Stay with me." (Genesis 29:18 - 20, HBFV throughout, see also Exodus 22:16 - 17 and Deuteronomy 22:28 - 29).
Many times a married or betrothal period lasted a year, but could be longer. During this time the couple lived apart (usually with their parents), which was the case with Mary and Joseph. The man and woman did not live together until the man came for her (see Matthew 25:6) and took her back to his home to consummate the marriage.
Betrothal is something like the modern practice of couples being "engaged" where they promise to marry each other. Instead of a partial payment of the bride price, the man usually buys the woman he has proposed to an engagement ring. There are, of course, major differences between being engaged in today's world versus being betrothed in Bible times.
As stated previously, betrothed couples (like Mary and Joseph) were considered, under God's law (intended to be applicable to all Israelites, and ultimately the world, not just to Jews), to be legally married.
If a man decided to end the relationship any time after the betrothal agreement is made (including after consummation), he had to pursue legal steps to do so.
When a man has taken a wife and married her, and it comes to pass that she finds no favor in his eyes because he has found some uncleanness in her, then let him write her a bill of divorce and put it in her hand, and send her out of his house. (Deuteronomy 24:1, see also Jeremiah 1:3, 8).
Unlike today, where sex before the wedding is anything but scandalous, the penalty for having sex during the period of betrothal could be punishable by the death penalty (Deuteronomy 22:23 - 24). This is something Joseph and Mary, being righteous, did not indulge in even though they were married.