Cameroon also fell behind against Mozambique in Agadir, but a thunderbolt from Christian Kofane delivered a 2-1 victory.
Defending champions Ivory Coast and Cameroon finished level on seven points and both had a plus two goal difference. The Ivorians topped the table because they scored five goals and Cameroon four.
The results completed the last 16 line-up: Ivory Coast will face Burkina Faso, Cameroon meet South Africa, and Mozambique face Nigeria.
In Marrakesh, Gabon took a two-goal lead against Ivory Coast midway through the first half before the title-holders cut the deficit to 2-1 at half-time.
Guelor Kanga struck after 11 minutes for Gabon, whose star Pierre-Emerick Aubameyang had returned to France for treatment of a thigh injury among polemics.
Ivory Coast fell further behind on 21 minutes when Denis Bouanga scored his first goal of the tournament and Jean-Philippe Krasso netted on 44 minutes.