Why do atoms repel when closer but attract when farther apart?

I see that you are going deeper into the rabbit hole and this might be a continuation of our previous disscusion on why solid matter behaves in the way rigid body dynamics suggests from a microscopic perspective.

Since in your previous question you said you where in highschool I'm not going to jump to the maths or abstract concepts behind this, but I'm going to try a more intuitive approach. The problem here is that in our previous discussion it was easy to keep us focused on classical mechanics, where physics is more or less intuitive (we all have some knowledge of what a force is and how a spring works), but here we have to deal with concepts that are completely out of any conceivable "common sense intuition"; concepts that have to be developed throughout many years at university, concepts that require heavy math and a fair amounts of easiness handling simplier but still complex concepts that constitute the foundations, concepts on quantum mechanics that are so out of touch with our everyday macroscopic experience of reality that many physicists just avoid trying to understand them in a conceptual manner and just adhere to the "Shut up and calculate!" doctrine. I'm saying this because what I'm about to tell you is not only an extreme oversimplification but I'm also going to need to use metaphors and other toy models that might be closer to our daily experience to explain this, and in doing so I want you to realize that they are just that, models, and all of what I'm going to say has to be taken with a grain of salt. The truth is that in mathematical language things are clear but when trying to use words things might get even to the absurd (since human languages have evolved to accomodate our everyday experience of the world and not this realm of reality) so please rememeber that everything has a correct and more rigorous explanation.


SIMILARITIES AND DIFFERENCES WITH SPRINGS

In classical mechanics we learn about potential energy. This is usually shown as some sort / "latent" form of the kinetic energy of an object, an energy that can be potentially unleashed and awaits to be converted into real kinetic energy. Here we have our first example of intuitive but imprecise approach to a physical concept.

The important thing is that potential energy is different in different contexts (situations in terms of space and time), depending on whether or not this energy has more or less potential to become kinetic energy. For example, a rock on the floor is usually regarded as having zero potentiall energy since there are no means to make it move (to see it gain kinetic energy) until someone acts on it. But a rock on the top of the empire state building has the potentiality to archive extreme amounts of kinetic energy as soon as it starts falling. As you can see my explanation suggest some kind of subjectivity to what it really means to have the potential to move but the reality is that potential energy is a well defined quantity in physics that has some notion of relativism in terms of where you place "the zero of the potential". I'm not going to expand further on this since it is not so usefull and it is some of the basics of classical mechanics.

My interest here is to explain that this dependence of the potential energy in terms of location, moment in time and other contextual parameters suggests a view of the world where potential energy constitutes a "landscape". Since force is the change in motion of an object and motion is associated to kinetic energy we can see that this "landscape" is in fact related to the behaviour of force. We tend to think about it like this: the slope on the terrain of the potential energy "landscape" tells us how much force (change in motion) is going to be at play at any time, the slope is in fact the rate at which potentiall energy might be converted to kinetic. Again this is oversimplified and can be missleading if you don't state assumptions, but for us this is enought. So, there's (usually) a direct relationship between force and this potential energy "landscape" in classical mechanics that is expressed as

$F = - \frac{dU}{dx}$

(in terms of words this tell us that the magnitude of the force $F$ on an object is the slope of the potential energy landscape, a.k.a. the rate of change of the potential energy $U$ with respect to the position of the object, $x$. This rate of change is expressed in maths as a derivative).

Force on springs is described by Hooke's Law, which states that

$F = -k (x-x_0)$

where $x$ is the length of the spring, $x_0$ is the length of the spring in the relaxed state and $k$ is a constant that defined the stiffness of the spring.

So, what is the potentiall energy landscape that corresponds to the force of a spring? We have to do the inverse operation of a derivative to get that (thus an integration), like this:

$U = -\int Fdx=-\int -k(x-x_0)dx=k\int x-x_0dx=k(x^2/2-x_0x)$

Which in a $U$ vs $x$ plot looks like this

enter image description here

The interesting thing is that these potential energy "landscapes" are very usefull in terms of giving some intuition on the evolution of the system. You can immagine a ball rolling down hill on this "lanscape" and relate that to the changing state of the system. In our case the ball could roll downhill (as we move throught the $x$ axis of the plot) and then continue uphill until the force brings it back downhill to the other side. This will make the so called harmonic oscillator, and springs are like that: if you contract them (low $x$) they are going to expand (to high $x$) and after expansion they are going to contract again in a never ending oscillation. In real life there are frictional interactions that would make this system to damp, so the ball finally gets to a static situation on the equilibrium point (the lower part of the valley). This equilibrium point is in fact reached when the spring is relaxed (no need for contraction and no need for expansion), or mathematically, when $x = x_0$ (which means $F=0$).

Great! So what shape does the intramolecular pontential landscape has? This one:

enter image description here

This is called the Lennard-Jones potential and as you can see is a bit more complex than the potential associated with a pring. They both share some qualitative commonalities; if you expand the spring (if you separate the atoms a little) it would try to contract (the atoms would atract each other) and if you try to contract the spring (get the atoms closer toghether) then it would try to expand (the atoms will repel each other). This is because both potentials look like a valley.

In fact both systems are oscillators (but the Lennard-Jones potential is not for a simple harmonic oscillator is just a bit different), this means that if you separate the atoms they are going to pull each other closer and by inertia they are going to surpass the equilibirum point and get to close toghether. In fact enought to start repeling each other and expand again in a periodic fashion. In fact the bonds between atoms in a molecule are generally oscillating, this vibrations inside molecules explain a lot of stuff in physics (why is the sky blue or how is temperature defined from a microscopic perspective). But if some dissipative process occurs (just like friction for the spring) the oscillation between the atoms in molecules and solids damps until the atoms reach an equilibrium distance (as the relaxation length of the spring).

But chemical bonds are not springs and in fact there are some key differences. As you can see the Hooke's potential is symetric but the Lennard-Jones is not. You can immagine it as a spring that reacts much more violently to a compression that to an expansion. You can also see (if you immagine a ball rolling down hill), that of you put the atoms very close toghether they are going to repel each other so much that they are going to get infinitely far (the bond can be broken by this method). This doesn't happen for the spring case, you can conpress it as much as you whish and after expanding it is going to return back. So in atoms there is a minumum energy to allow the complete disruption of the connected system of a molecule but this doesn't happen on springs. All of this can be seen just by the shape of this potential.

So, we know the potential of an harmonic oscillator (the Hooke's potential) comes from a mechanical force related to elastic tension on a spring and described by Hooke's Law. But what is the nature of the force that generates the Lennard-Jones potential? Well, the asymetric nature of it suggests that maybe there are two different causes (one force might explain the resistance to expansion of the bonds and the other, completely different in nature, might explain the resistance to contraction of the bonds), and indeed this is the case. So let's get into each cause separately.


ATRACTION

One might think that the atraction between two atoms is explained by Coulomb's Law in a direct way since electrical charges and electrical forces are at play, but the truth is more complex. Coulomb's law says that for two charges ($q_1$ and $q_2$) there is an electricl force like so:

$F = k_e\frac{q_1q_2}{x^2}$

where $k_e = 9×10^9\; N\;m^2/C^2$ is a constant of nature called Coulomb's constant, and $x$ is again the separation between charges.

The important thing here is to note that the force is proportional to $x^{-2}$. So if we get two opposing charges twice as close the force of attraction is going to be $2^2=4$ times stronger.

This looks very similar to gravitational interaction but the key difference is that the "gravitational charge", mass, is always positive while electrical charge can be of two kinds. This means that you can concentrate charges in such a way as to shield each other to make the entire ensemble neutral (without charge). You can't do this with mass since there is no way to add mass to an object and stop being attracted to it.

Atoms in a solid are generally neutral, This is because the electron charge is the same as the proton charge and thus any atom with the same number of electrons and protons is neutral overall. There is no Coulombian reason in sight as to why they should atract each other.

But the thing is that things are more subtle. There are two phenomena at play; Van der Waals forces and London dispersion forces. Both are rooted in Coulumb's law in fact. The thing is that atoms, even if neutral, might get polarized. This means that the charges inside them might be displaced when another charge gets close to the atom. Suppose an electron getting closer to an Hydrogen atom (one proton and one electron), this incoming electron will repel the electron inside the atom and atract the proton on the nucleus, the force is tiny (since the binding force between the electron and proton in the atom is huge due to their vicinity) so the atom wouldn't shatter into pieces, but is enought to create an imbalance in the disposition of the charge inside the atom. This doesn't mean that the electron on the atom gets to the opposite side of the atom as the other electron comes closer, it means, that on average, the electron will be located more on the opposite side of the atom. This polarity thing is what generates the Van der Waals forces and surprisingly, if you do the math, you can see that this force (which is an emergent property rooted in Coulumb's interaction) is not dependant on $x^{-2}$ as Coulumb's interaction is, but it turns out it is dependant on $x^{-6}$!

London dispersion forces are similar in nature. This polarity thing oscillates and fluctuates in such a way that the overall noise is equivalent to a specific charge been in place of the neutral atom. The details are very complex and again you need to understand quantum mechanics. Bu these forces are also dependant on $x^{-6}$.

So, we can conclude that both, Van der Waals and London dispersion forces are the causes of the atraction between atoms and this atraction is inversely proportional to the sixth power of the separation between atoms:

$F \propto 1/x^6$

The associated potential landscape looks like this:

enter image description here

Which makes total sense. If you drop a ball on this terrain it will fall towards the left (smaller $x$), just as the atraction of two atoms due to Van der Waals and London forces would shrink their relative distance $x$ quickly as they get closer.


REPULSION

Your scheme for what causes repulsion is not correct. Even more, the model of the atom you are using is one of the first models for the atom, the so called Rutherford atomic model. This model was one of the first attempts to make sense of the structure of atoms, but is very primitive (it predates quantum mechanics) and makes awful predictions (like the fact that atoms only exist as breifly as some nanoseconds according to the model). The model explains the atom as a miniature Solar System with electrons orbiting the nucleus by means of Coulumb's force. The electron circles around like a classical particle.

The Rutherford model was succeded by Bohr's model and eventually by Schödinger's model of the atom (which is a model with inmense predictability powers and the one we usually learn at University). These new models where quantum in nature and things got weirder. Instead of immagining the electron as a planet orbiting a star you have to immagine that the probability of finding the electron somewhere in the space surrounding the nucleus generates what we call an electron cloud. Let me explain. In quantum mechanics the word "probability" doesn't mean what we generally think, it is not the fact that the electron might be somwhere but we really don't know so we assign probabilities to each possible position of it, NO!, it is more like the electron has a position that is intrinsically undefined, its existence is spreaded out throught space. Instead of "probability of finding the electron here and there" it might be more useful to think of this as the "quantity of existence"/presence of the electron throught space. The map that defines the quantity of existence of the electron is called the wave function. This "map of existence" is called like that because the map changes over time and as it turns out it changes in a way that resembles the behaviour of a wave. This is difficult to grasp and using words as "wave", "quantity of existence", etc... is dangerous because it rings a bell inside our minds and recalls diffuse and inaccurate images of what is really going on (which we know with high accuracy and concreteness). I'm trying to plain-speak about something that is not possible to understand with our preconceived classical notions of the world so we have to be careful to avoid falling into the pseudoscientific mumbo jumbo. In fact an entire field of study inside quantum mechanics is about what philosophical implications can or can't be brought and how the theory should be interpreted. The thing is that in some interpretations things are not 100% existent or 100% non-existent, but there is a gradient of existence from 0% to 100% for each characteristic of a physical object. The position of the electron is not 100% determined, there is some quantity of existence for the electron in each point in space, far from the atom the electron exist very little for example, and the region of where the electron existence is spreaded predominantly is what we call the electron cloud. Again this region is defined by this map of existence we call the wave function. this map varies in time unless the wave is stationary like in the simple non-excited atom. Electron clouds don't even have the shape of an orbit or a spherical carcass in many cases, they can be very complex in shape. So your model of the atom is just as accurate to explain what you want to adress as a snowman is accurate as a model of a human to explain what emotions are.

So, from where is this repulsive force coming? Well, it turns out that if you play enough with the mathematical foundations of quantum mechanics you arrive to the idea of Pauli exclusion. This principle states that two identical fermions (which are a specific kind of particle) can't occupy the same quantum state. For our specific case this means that no two electrons should occupy the same location in space. Electrons are fermions but there are particles that do not obey this principle, for example, photons (which are not fermions but bosons) and can indeed occupy the same place. The thing is that as we interpret what an electron is it becomes difficult to state that the electron occupies some specific place in space, since its quantity of existence is spreaded across space. Therefore what exactly means that two electrons can't occupy the same place? Well, as it turns out it means that there is a repulsion between them that is proportional to the overlapping of the spreads of their existence. This phrasing is getting weirder but maybe with this we can at least make some insight on the problem. The end result is the so called Pauli repulsive force. We are not going to explain how this is inferred from the postulates of quantum mechanics nor we are going to make any reasonable path without math but at least you can have some intuition of what is going on with these images.

The repulsive force due to Pauli exclusion is what emerges when you try to get two electron clouds (the regions where the electrons are primarily existing) closer together. It turns out that this repulsive force is proportional to the inverse of the twelfth power of the separation between the electron clouds!

$F \propto 1/x^{12}$

This strong dependance (way stronger than the one atracting both atoms) on the distance means that if you separate the atoms by not too much it is basically non-existent but if you get them close then the force skyrockets like if there was a huge barrier. For the Van der Waals and London forces we had that putting the atoms twice as close resulted in $2^6=64$ times stronger atraction but now for the Pauli force we have that if you get twice as close the repulsion is $2^{12}=4096$ times stronger. So they behave in similar ways but the Pauli force is extremely sensitive in comparison.

We can draw the corresponding "landscape" for the potential associated with this force like this:

enter image description here

As you can see it is not only repulsive (a ball in this terrain will fall towards the right quickly; the separation between the atoms $x$ will increase rapidly) but very pronunced in comparison to the atraction potential. It is clearly only noticiable for small $x$ (at close ranges), and it is undetectable for larger separations.


PUTTING EVERYTHING TOGETHER

Finally we are able to see what is going on here. There is a combined Van der Waals and London atracting interaction between the atoms due to asymetries generated on the electron clouds of both atoms in the distribution of charge, and there is a repulsive interaction due to Pauli's exclusion principle. Both phenomena can be added together (the atraction with a negative sign since the force tries to of atraction is trying to decrease $x$ and the repulsion with a positive sign for the opposite reason) and show us that the total force on each atom has the form

$F = A/x^{12}-B/x^6$

Where $A$ and $B$ are proportionality constants that vary for each interaction. Different atoms have different $A$s and $B$s depending on their atomic number and number of electron.

Look at that equation it is obvious that for large $x$ both fractions turn to zero, and in fact for large separations the atoms feel no force. For small $x$ both fractions get big, but the first fraction gets a lot bigger more repidly so it dominates the interaction, and in fact if the atoms are very close the repulsion is way larger than the atraction (even if both are huge). There has to be some kind of equilibrium point in between both extremes, an $x$ for which the force is actually zero:

If $F = 0$ then $A/x^{12}=B/x^6$ and therefore $x = \sqrt[6]{A/B}$. At this distance the attraction and the repulsion balance each other. As you can see this equilibirum separation (which determines the length of the chemical bond) is dependant on the parameters $A$ and $B$. That is the reason that different atoms make stronger or weaker bonds, with larger or smaller separation between the atoms. This is also related with the oscillations that happen in molecules (which we might treat in a simplistic way as the $k$ stiffness coeficient of a mechanical spring).

Finally we can see all of this as a landscape of the potential energy. We have to combine our previous two curves by mere adition.

enter image description here

Summary: the black curve is the Lennard-Jones potential between two atoms, which is decomposed into the atractive potential (blue curve) and the repulsive potential (red curve).

This is why we can, to some approximation treat the interaction as a spring. Because it has similarities to the parabolic potential of a spring.

Lastly I want to reccomend to you once again "The Mechanical Universe" series. They explain the basics of everything you should understand before getting into university level physics. They explain this spring-like behaviour of atomic bonds with simple animations: