I did not realize that Spain is not using standard gauge tracks.
Both Spain and Portugal use Iberian gauge of 1668 mm, except on newer high speed lines built to standard gauge. Apparently, Spain original adopted a gauge of 1672 mm or 6 "Castilian feet", while Portugal built to 1664 mm or 5 "Portuguese feet". 1668 mm just happens to be in the middle when they standardized between themselves.
As a side note, there are some really cool gauge changing trains running between Spain and the rest of Europe:
Gauge changing explained at 2:20: