Two or more quarks close to each other rapidly exchange gluons, creating a very strong "color force field" binding the quarks together. There are three color charges, and three corresponding anti-color (complementary color) charges. Quarks constantly change their color charge as they exchange gluons with other quarks.
Not until the development of the Standard Model's theory of the strong interactions could physicists explain why the quarks combine only into baryons (three quark objects), and mesons (quark-antiquark objects), but not, for example, four quark objects. Now we understand that only those combinations are color neutral. Particles such as ud or dd that cannot be combined into color-neutral states are never observed experimentally.
If one of the quarks in a given hadron is pulled away from its neighbors, the color-force field "stretches" between that quark and its neighbors. In so doing, more and more energy is added to the color-force field as the quarks are pulled apart. At some point, it is energetically cheaper for the color-force field to "snap" into two new quarks. In so doing, energy is conserved because the energy of the color-force field is converted into the mass of the new quarks, and the color-force field can "relax" back to an unstretched state.