The ruling in the case brought by two mothers, Reetha Suppiah and Sakinet Bello, said the detention of the families following dawn raids on their homes breached their right to liberty and to family life under Articles 5 and 8 of the Human Rights Act 1988.
The court also highlighted that the detention of children is capable of causing significant and long-lasting harm to them.
In his ruling, Justice Wyn Williams said: "No one can seriously dispute that detention is capable of causing significant and, in some instances, long lasting harm to children.
"The cases of the two families involved in this litigation provide good examples of the failure by UKBA to apply important aspects of the policy both when the decisions were taken to detain each family and when decisions were taken to maintain detention after removal directions had been cancelled."
Penny Nicholls, director for children and young people at The Children's Society, said the judgement added pressure on the government to bring forward its goal of completely ending child detention, which has been set for May.
"This case highlights once more that immigration detention of children should be ended immediately," she said. "It is disappointing that, given the vast body of evidence of the harm experienced by children in detention, we continue to see children detained. However, we are encouraged that the government has committed to ending the detention of children in immigration removal centres, and we are keen to work with them to ensure that cases like this become a thing of the past."