What exactly is a cavity? That's a great question, because it's hard to figure out how to prevent something, when you don't know what it is in the first place.
Teeth are made up mostly of calcium, which makes them rock hard.
(There is also an inner organic, live component, including nerve fibers and blood vessels, but that doesn't concern us here. At least, not until you get a cavity. Then it counts, big time!)
A cavity occurs when the bacteria, which are always in your mouth, eat and digest any food debris that is left over after eating.
These bacteria will produce acids as a waste product. (Yuck. That alone may make you want to brush and floss better.) These acids will dissolve the calcium in your teeth and create cavities. So, a cavity is essentially a decalcification, a dissolving of your tooth by acid produced by bacteria, which are just having a meal of "leftovers".
The cavity, being a hole in your tooth, will now trap more food and bacteria than before, and is harder for you to clean, so it tends to get bigger pretty quickly.
If it gets deep enough, it will get close to the nerve, which will let you know that it's not happy, especially when you eat or drink cold, hot, or sweet things.