WASHINGTON—The Supreme Court on Friday ruled same-sex couples nationwide have a constitutional right to marry, a landmark decision that sweeps away state bans on gay unions and caps a rapid American transformation on the meaning of marriage.

The 5-4 decision written by Justice Anthony Kennedy, his fourth major gay-rights ruling over two decades, struck down restrictions in force in 13 states and means all 50 states must recognize same-sex unions. The court was considering a challenge to laws in Kentucky, Michigan, Ohio and...