Often said but it is more complex than that.
Sticking to this issue rather than attempting a more general explanation, the view of the courts is that, particularly when dealing with criminal offences, the law needs to give certainty. People should be able to know in advance whether their conduct could constitute a criminal offence. If the law is clear and capable of being understood by the average person, the fact you don't know the law may not be a defence (although it sometimes can be even in this situation). However, if the law is unclear and the average person has no way of knowing what is required to comply with the law, that is likely to be a complete defence.
When dealing with single-sex spaces, an employer was faced with both the EHRC and the HSE taking the position that it was illegal to exclude trans women from women-only spaces. There were a number of instances of the lower courts endorsing that view, including an attempt to challenge the EHRC guidance through judicial review which failed, with the judge saying that the case against the EHRC was unarguable. Against that background, how was an employer supposed to know that they were breaking the law by admitting trans women into women-only spaces? Seeking legal advice wouldn't help as most lawyers, given the decisions by the courts, would have advised employers to let employees use the facilities that matched their acquired gender. Indeed, I wouldn't be surprised to find that some insurers were telling employers they must follow this interpretation of the law, or their insurance would be void.
The Supreme Court has now said that the lower courts, the EHRC and the HSE were wrong, so it was always an offence for an employer to allow trans women into women-only spaces (and, indeed, trans men into men-only spaces). However, if it wasn't possible for an employer to know that with certainty at the time, they cannot be found guilty of a criminal offence even though they have committed one. In the view of the courts, that would be the same as passing a law that retrospectively made vaping a criminal offence and prosecuting anyone who has ever vaped.