Can you determine the weight of something just by resolving how big it looks through the telescope? Not quite, but this is how the measurement of the mass of an object begins. Astronomers make a rough estimate of what hides inside planets and stars, and knowing the density of each element they can make a first approximation of its weight. We know what hides inside planets and stars, but we don’t know exactly how extensive each layer is. To be frank, we don’t even know how big Earth’s core is, at least not exactly.
To figure out the composition of what is inside our planet, or other planets in the solar system, we deploy a set of methods. First, we observe the seismic activity and measure how turbulences and shakes propagate from one side of the planet to the other. Secondly, we can observe and measure the orbiting of the planets in relation to the Sun, or each other, and figure out the masses from the gravitational forces that come into play.
Something similar applies to measuring the mass of galaxies and the distant stars that constitute them. The trajectories of the stars and how they move around the center of the galaxy can give away their masses, and thus, the total weight. When a distant star sends us its light and we notice distortion or “lensing”, it means that a pretty massive object, like a black hole for example, sits in between. By measuring the deviation in the light’s path we can figure out how much a black hole weighs.
Finally, when measuring everything in the universe, especially massive objects and distant galaxies, we account for the dark matter that is there, which is 27% of the total mass. We can’t see it directly, but it’s there, and becomes evident when galaxies collide for example. It was first assummed when astronomers couldn’t figure out how galaxies hold together thanks to the gravitational forces alone and based on the masses they observed.