Spain initially sided against France in the Napoleonic Wars, but the defeat of her army early in the war led to Charles IV's pragmatic decision to align with the revolutionary French. Spain was put under a British blockade, and her colonies—for the first time separated from their colonial rulers—began to trade independently with Britain. The defeat of the British invasions of the River Plate in South America emboldened an independent attitude in Spain's American colonies. A major Franco-Spanish fleet was annihilated, at the decisive Battle of Trafalgar in 1805, prompting the vacillating king of Spain to reconsider his alliance with France. Spain broke off from the Continental System temporarily, and Napoleon—aggravated with the Bourbon kings of Spain—invaded Spain in 1808 and deposed Ferdinand VII, who had just been on the throne forty-eight days after his father's abdication in March.
The Spanish people vigorously resisted Napoleon's move, and juntas were formed across Spain that pronounced themselves in favor of Ferdinand VII. Initially, the juntas declared their support for Ferdinand VII, and convened a "General and Extraordinary Cortes" for all the kingdoms of the Spanish Monarchy. The Cortes assembled in 1810 and took refuge at Cádiz. In 1812 the Cádiz Cortes created the first modern Spanish constitution, the Constitution of 1812 (informally named La Pepa).
The British, led by the Duke of Wellington, fought Napoleon's forces in the Peninsular War, with Joseph Bonaparte ruling as king at Madrid. The brutal war was one of the first guerrilla wars in modern Western history; French supply lines stretching across Spain were mauled repeatedly by Spanish guerrillas. The war in the Iberian Peninsula fluctuated repeatedly, with Wellington spending several years behind his fortresses in Portugal while launching occasional campaigns into Spain. The French were decisively defeated at the Battle of Vitoria in 1813, and the following year, Ferdinand VII was restored as King of Spain.