You should first consider whether you can just use an Aspect Ratio Fitter component on the child to take care of this for you. There is a “fit in parent” option. I have heard that Unity’s implementation of this is kinda inefficient, though, so if you need this behavior for a lot of objects you might want to do some performance testing.
If you want to write your own script, you’d need to scale the child down by a ratio of (parent size) / (child size). If you want to preserve aspect ratio while fitting within the parent, then scale both the width and the height by whichever ratio is smaller.
The size of UI objects is a bit tricky because they sort of have two “sizes”–they have sizeDelta, and also scale. So (A) you should think about which one of those things you want to modify in the child, and (B) if you want to fully cover your bases, you need to take both of those into account when calculating your scaling ratio in the first place.