The first thing you need to understand nebulae is that the space between stars and Star Systems isn’t a vacuum or empty. There’s plenty of nitrogen, hydrogen, and other gases floating around. It just happens to be very disperse, making it seem empty. We call this space the interstellar medium, or ISM. Nebulae are formed in the interstellar medium, that is the semi-empty space between star systems.
Source