Mary and Joseph did everything in their power to hide the fact that Mary was pregnant through a virgin birth. How in the world did the gospel writers find out?
The Bible does not tell us everything about Joseph and Mary’s actions regarding her miraculous pregnancy. We do know that Joseph was interested in sparing Mary from “public disgrace” (Matthew 1:19).
In the beginning of his gospel, the evangelist Luke states: “Many have undertaken to draw up an account of the things that have been fulfilled among us, just as they were handed down to us by those who from the first were eyewitnesses and servants of the word. With this in mind, since I myself have carefully investigated everything from the beginning, I too decided to write an orderly account for you, most excellent Theophilus, so that you may know the certainty of the things you have been taught” (Luke 1:1-4). Did that investigation include speaking to Mary? We do not know.
We do know that Jesus, on the cross, instructed John to take care of Mary (John 19:25-27). Did John at some point relay information from Mary to Luke? We do not know that either.
At any rate, we want to keep in mind that the doctrine of verbal inspiration means that the Bible writers wrote down exactly—to the very word (1 Corinthians 2:13)—what God wanted them to write down. They might have received their information directly from God that even covered events well before their lifetimes. (Think of Moses writing about creation.) The Holy Spirit is responsible for the Bible’s contents. (2 Peter 1:20-21)