The decision was 5-4, written by Justice Anthony Kennedy.
The law helps determine who is covered by more than 1,100 federal laws, programs and benefits, including Social Security survivor benefits, immigration rights and family leave.
The ruling comes as states are authorizing gay marriage with increasing speed — 12 plus the District of Columbia now allow it — and with public opinion having turned narrowly in favor of gay marriage.
Under the law, gay couples who are legally married in their states were not considered married in the eyes of the federal government, and were ineligible for the federal benefits that come with marriage.
The case before the Supreme Court, U.S. v. Windsor, concerned Edith Windsor and Thea Spyer, a lesbian couple who lived together in New York for 44 years and married in Canada in 2007.
When Spyer died in 2009, Windsor was hit with $363,000 in federal estate taxes. Had the couple been considered by the federal government to be married, Windsor would not have incurred those taxes.