I want to add that the law stated that not giving your brother's widow children was public humiliation, not death (Deut. 25:7–10). But Onan received death as punishment for his crime. Why? He lost his life because he violated natural law.
I'll agree with that and also add why his violation of natural law was so bad that God killed him for it.
(I'm repeating myself from another post)
I'm of the thinking that Onan did not impregnate Tamar because he knew that if she had a male child, it would be Er's and that child would receive the double portion and blessing from Judah. And Onan - who was now, with Er's death, the oldest male child - thought himself to be the inheriter of the double blessing and wanted it for himself. He enjoyed sex with Tamar but ejaculated on the ground so as to avoid losing his dead brother's inheritance that would go to him, if no son for Er was produced.
Onan was greeeeeedy little man. Greedy for sex on his terms and greed for his father's wealth.
The sin here wasn't one of making a decison to not have a child or birth control all by itself. The sin was [1] disobedience to God, [2] dishonoring the law of the levirate marriage, [3] dishonoring one's father (Judah told Onan to take Tamar in), and [4] dishonoring one's wife (Judah told Onan that he had a duty to her) and [5] the sin of keeping her a childless woman with no security - that would have put her in a bad place.
And, in my opinion, the overarching sin was the sin of greed - a selfish greed that would have and did cause disrespect and harm to others.