How do we know which background and foreground colors work well together?
Aesthetically, color theory is a rather involved graphic design topic. For web developers who are interested in learning about graphic design I recommend “The Non-Designer’s Design Book”.
This tool can be used to create color palettes that work well together. For improved accessibility, be sure that your background and foreground colors pass a contrast check.