There are two ways - both covered above but here is a little more detail.
First is that they get you to buy an "after the event" (ATE) insurance policy. This policy pays the costs of fighting to trial irrespective of result.
Secondly, they enter into a contingency fee agreement (ie no win no fee). Thus if you win (ie settle before trial or win at trial) the other side pay the costs. If you do not win, then the solicitors have done it "at risk" and receive nothing for the work they have done. However, generally speaking a solicitor will only take on a no win no fee case if he has a very good chance of winning.
Generally speaking these such firms will use a combination of both of these methods.