Sometimes the song matches perfectly with the opening like the beginning of Little Witch Academia, so I was wondering if the art for the opening was done then the song was made to match the art, or if the song was created, and the artists made the opening based off the song?
In this particular case, it seems the song was recorded first.
Generally, it differs. Traditionally, voice acting and drawing were independent of each other, both being dependent on the story board.
Then one movie came out which had the voice acting done first and then after that the drawing, so that the animated lips would match the (Japanese) text. This was a huge revolution at the time. I believe that film was Ghost in the Shell, although I cannot find a reference to back up that claim.
Having the drawing matching the voice acting means more work, means more expensive. Additionally, since voice acting needs to be done first, both can't work parallel the whole time, so production time is longer, which also means more expensive. Because not doing production in that strict order is cheaper, you usually see it employed in most anime, except for special occasions like openings, which can be reused multiple times.
Here is some knowledge. Rose Ridge's comment is also an answer.
Artists, Songwritters, Producers, Employees, Voice Actors, Freelancers, Directors all work in groups. Depend on them want to work in specific field or handle multiple tasks.
Mostly creation of idea first, stordboard, song are tributes with arts or finding songwritters for match art or art idea come from a song (depend) , final art. Animatic done then song, after that animatic match with song, then finalize art match sound & timing, published.
Creative industries doesn't have a really logical work flow like finances or others.
All is depend on song or art first. We will never know the production steps of the industry, unless an employee already corporated with them to see their progression via proposals, gantt chart etc. and majority of proposals are private under working purpose. But mostly progression will never write about song first or art first, mostly idea development recorded at first time.
If the art done based off the song, the song can be a background music. If a song done based off the drawing, the pre-production of live boardcasting will not have any storyboard plan at that time but still have art & design for video. All arts no matter song or drawing are arts, need to work together to have a final product.
Some of the information contained in this post requires additional references. Please edit to add citations to reliable sources that support the assertions made here. Unsourced material may be disputed or deleted.