This is how the birth of Jesus Christ came about:
When his mother Mary was betrothed to Joseph, but before they lived together, she was found with child through the Holy Spirit.
Joseph her husband, since he was a righteous man, yet unwilling to expose her to shame, decided to divorce her quietly.
Such was his intention when, behold, the angel of the Lord appeared to him in a dream and said, "Joseph, son of David, do not be afraid to take Mary your wife into your home. For it is through the Holy Spirit that this child has been conceived in her. She will bear a son and you are to name him Jesus, because he will save his people from their sins."
All this took place to fulfill what the Lord had said through the prophet: Behold, the virgin shall conceive and bear a son, and they shall name him Emmanuel, which means "God is with us."
When Joseph awoke, he did as the angel of the Lord had commanded him and took his wife into his home. Matt 1:18-24
Not much is written about Joseph in the Bible. We know that Mary was born without sin. Tradition also tells us that she was young, maybe even very young when she was "found with child". The age of fifteen or sixteen is often suggested. Being young and without sin, it is possible that she was not fully aware of the stigma of conceiving a child out-of-wedlock in that time and place.
It is speculated that Joseph was a widower and had older children who needed care and that he had a household to be run. The Biblical evidence is thin, but later passages in the Bible mention of Jesus's brothers and the implication is that they are not very fond of him. Joseph-as-a-widower is a tidy reconciliation of "Mary ever-virgin" and Jesus having siblings. The fact that Jesus was the reason their father went to Egypt for a few years, abandoning the siblings to the care of aunts and uncles would also fuel sibling tensions.
Consider that Joseph grew up in Nazareth, a small village with almost no mobility. Consider that every adult in that village could count and perform elementary subtraction and knew that Jesus had been born less than a full nine months after Mary "officially" co-habitated with Joseph.
Every adult in that village doubtlessly concluded that Joseph was not an honorable man. That conclusion undoubtedly impacted Joseph's ability to get work. Would you trust a tradesman when concrete evidence in the form of young Jesus was running and hollering about the village, evidence that Joseph was not patient, could not follow the law and would cut corners when he thought nobody was looking?
Joseph was not young. He knew that people in small villages have little to do but gossip. He was painfully aware of the economic consequences of marrying Mary and giving legitimacy to her pregnancy.
He did it anyway.