The halocline and sonar
Because of the limitations of wartime sonar, U-boats could sometimes pass undetected into the Mediterranean through the Straits of Gibraltar, but it was always risky and avoiding detection couldn't be guaranteed. 

There were many things that limited the efficiency of sonar (or ASDIC as the British called it). It is true that sea water has a tendency to separate itself into layers which sonar finds difficult to penetrate. Sometimes this layering was based on differences in salinity, sometimes on differences in temperature, and sometimes on intervening sea currents. Even ships wakes could deflect the sonar beam, so sometimes powerful curving wakes were deliberately made by the U-boat to shake off a pursuing warship.

The range of active sonar under good conditions was normally a few miles, but that could be reduced if there was a lot of background noise. The Gibraltar straits are about 12 miles wide.  Whales and schools of fish could also send back false echoes which would fool all but the most experienced sonar operators.