Mexico, who will face Group B winners Netherlands in Fortaleza on Sunday, had looked happy to hold out for the draw that would have seen them into the knockout stages, before the Manchester United forward came on to turn the match on its head. Within 10 minutes, Rafael Marquez put Mexico ahead with a powerful header, before Andres Guardado rounded off a swift counter attack and Hernandez himself finished with a close-range header.
Mexico briefly flirted with top spot in the group, needing one more goal to depose Brazil before the hosts got a fourth against Cameroon.
But Ivan Perisic then grabbed a late consolation for Croatia who had substitute Ante Rebic sent off in the dying stages for a poor challenge.
Mexico started strongly; Hector Herrera rattled the crossbar with a vicious left-foot drive from distance after 15 minutes but the second half was almost entirely controlled by the men in green. After they had a penalty appeal turned down, they took the lead with 18 minutes to play.
Captain Marquez rose powerfully in the area to head a cross from the left into the bottom corner.
Three minutes later and the largely Mexican crowd were rocking in the aisles as Guardado was allowed to arrive unmarked at the far post and finish off a sweeping counter attack with a crisp finish past Croatia goalkeeper Stipe Pletikosa. Hernandez had the last word, with eight minutes remaining, heading a Marquez flick-on from a corner into an unguarded goal.