There have been many theories about the origin of the Earth and of life, some religious, some scientific, and others a blend of both. The scientific theory that is in vogue at the present time is called the Big Bang Hypothesis. It is thought that 12-15 billion years ago, all matter was compressed into a space the size of our sun. A sudden instantaneous distribution of matter and energy throughout the known universe occurred. The Earth was formed about 4.6 to 4.5 billion years ago when minerals and ice orbiting the sun started clumping together. Heavy metals moved to the Earth's interior, lighter ones floated to the surface. This produced the outer crust and inner mantle.
The Earth is "just right" for life. If it was smaller in diameter, gravity would not be great enough to hold onto the atmosphere. If it were closer to the sun, water would have evaporated. If it was farther from sun, water would have been locked up as ice.