The "Beckham Law" is a Spanish tax law that was passed in 2005. The law gained its nickname after football player David Beckham became one of the first foreigners to take advantage of it.
Previous to the Beckham Law, any foreign worker remaining in the country over 183 days in a tax year was deemed to be "tax resident" which meant they were liable for Spanish taxes on their worldwide income, not just their Spanish source income and assets.
With the Beckham Law, an expat can apply to be taxed as a non-Spanish resident under the Spanish Non-Resident Income Tax rules, which means they will only be taxed on income they earn in Spain, and not on income they may continue to earn elsewhere in the world. Under this exemption, the expat would be subject to a flat 24% tax rate up to 600,000€, rather than the progressive tax rates applicable to Spanish residents. If taxed as a resident, the expat would be subject to a progressive tax scale ranging from 15% to 43% depending on their level of income.
Note that this is not a loophole or tax evasion tool: the capital gains earned outside Spain must still be paid in the country where the earnings originated. If they were earned in a tax haven, then the earnings must be paid in Spain. This is not a "gray area". It is totally regulated and transparent. In Spain, as elsewhere, tax fraud is a serious crime.