Most clubs in La Liga award the captaincy to the player who is the longest serving at the club.
Since Casillas had been with Real Madrid as a youth since 1990 and made his first team debut in 1999 he always held seniority over Ramos, who arrived at the club in 2005. Any time the two were on the pitch together, Casillas had seniority.
Ramos assumed the captaincy once Casillas left for Porto in 2015.
In the case of the Spanish national team, the captaincy is awarded to the player with the most international appearances (as do Portugal and Italy).
In every instance when Casillas and Ramos played together with Spain Casillas always had more international appearances, thus ranked ahead of Ramos in the order of captaincy.
(Fwiw, Casillas took over the Spain captaincy after Raul was no longer selected following the 2006 World Cup.)
As of this post Casillas still has more appearances with Spain than Ramos (167 to 165) so if Casillas was to be recalled today he would regain the captain's armband.
But If Ramos continues to play for Spain and Casillas isn't recalled until, say, 2020 Ramos would pass Casillas in the number of Spain appearances and would thus maintain the captaincy... unless he wishes to give it back to Casillas which would be his decision to make.
If Ramos was to retire from or no longer be selected to the national team the armband would go the current squad member with the next most appearances, which as of now would be Sergio Busquets.
Likewise, if Ramos was to leave Real Madrid the captaincy would go to the next longest serving player at the club which would currently be Marcelo followed by Karim Benzema then Raphaël Varane.