researchers have shown that when really small particles are close to each other like in a nebula, they are attracted to each other due to electromagnetism (from static electricity) since the masses are too small for gravity to really matter. However, the answer is probably gravity, electromagnetism only played a small role in the very beginning when nothing had enough mass. After that, gravity caused everything to condense and gravity did a better job once everything had enough mass for gravity to matter.
I hope this helps, let me know if anything is unclear in the comments.