The Sack of King's Landing came during the end of Robert's Rebellion, also known as the War of the Usurper, in which Robert Baratheon, Eddard Stark, and Jon Arryn led their armies against the Targaryens on the Iron Throne.
House Lannister under Tywin Lannister had delayed declaring for one side or the other, but when it became obvious that the rebellion was going to prevail, he marched his forces to King's Landing on the pretense of coming to aid Aerys. Grand Maester Pycelle (long secretly loyal to Tywin Lannister) advised Aerys to open the gates, Varys advised not to. Aerys listened to Pycelle, the Lannisters began plundering, raping, and destroying all in their path. During this time, the Mad King Aerys was killed by the Kingsguard member Jaime Lannister. He killed Aerys to prevent him from exploding wildfire throughout the city (Aerys had arranged that if the city fell, he would reduce it to ashes). Ser Jaime then waited on the Iron Throne to see who would claim it. During the sack, Lannister men broke into Maegor's Holdfast and murdered Rhaenys Targaryen, daughter of Rhaegar and Elia of Dorne. Gregor Clegane killed Aegon Targaryen, Elia's son, and then raped Elia before he killed her as well. Eventually, Eddard Stark arrived with his men to claim the throne for Robert Baratheon the Usurper, and the war ended.
Eddard Stark and Jon Arryn decided to stand aside and let Robert be king. Robert had the best claim, as he had Targaryen blood from both his grandmother and the whole Baratheon line started with a Targaryen bastard line. Jon Arryn was older and Eddard was quiet and just wanted to return to the North. Robert was charismatic and Jon Arryn believed he would serve best as Hand of the King.