King Philip IV of Spain died in 1665, leaving behind only one surviving son, Charles, who became Charles II. Charles II — disfigured and mentally challenged — ascended the throne at the wee age of 4, the last of the Spanish Hapsburgs. He came to be known as El Hechizado,
"The Bewitched," because it was popularly believed that his disfigurement was caused by sorcery. (It was more likely caused by generations of inbreeding.) So as not to overtax him physically or mentally, he was left totally uneducated and not even expected to keep himself clean.
Because of his unfitness to rule, Charles's declarations were largely ignored, and the Spanish monarchy was greatly influenced by outside forces, particularly from France, and the Spanish kingdom saw a great decline during his reign. Because of his physical and mental deficiencies, Charles II left no heirs. In his will, Charles left all of his possessions to Philip, duc d'Anjou, grandson of Louis XIV, King of France. When Charles II died in late 1700, Philip thus became Philip V, King of Spain.
With the current monarchy of Spain extending directly from the French bloodline, Louis XIV saw an opportunity to expand the French empire, threatening the balance of power in Europe. Holy Roman Emperor Leopold I fought for his bloodline's (somewhat justified) claim on the Spanish throne, more in an attempt keep France in check than for personal gain. Other governments quickly took sides — mostly against France and Spain — and thus began the War of Spanish Succession.
In the end — with the signing of the treaties of Utrecht, Rastatt, and Baden in 1713 and 1714 — Philip was recognized throughout Europe as Philip V, King of Spain, but was forced to renounce his place in the line of French succession. Although Spain retained its possessions overseas, it gave up Gibraltar, Milan, Minorca, Naples, Sardinia, Sicily, and the Spanish Netherlands. It also granted Great Britain exclusive rights for 30 years to the slave trade in Spanish America, an arrangement known as the asiento.