Solution 1:

It is valid to mod out arguments of a fraction - just like it is for the arguments sums and products

Lemma $ $ If $\,(B,n)= 1\,$ then $\bmod n\!:\,\ \begin{align}A\equiv a\\ B\equiv b\end{align}\,\Rightarrow\, \dfrac{A}B\,\overset{\rm def}\equiv A \color{#c00}{B^{-1}}\equiv a\color{#c00}{b^{-1}}\,\overset{\rm def}\equiv\, \dfrac{a}b$

Proof $\, $ Scaling $\, b\equiv B\,$ by $\,b^{-1}B^{-1}\Rightarrow \color{#c00}{B^{-1}\equiv b^{-1}}\,$ by CPR = Congruence Product Rule, so multiplying this by $\, A\equiv a\,$ yields $\, A\color{#c00}{B^{-1}}\equiv a\color{#c00}{b^{-1}}$ again by CPR. $ $ Note $b^{-1}$ exists since $\,b\equiv B\pmod{n}\Rightarrow (b,n) = (B,n)=1$

Thus the answer to your question as to "why it works" is that unwinding the definition of a fraction yields a composition of a product and inverse operation - and those operations are "compatible" with modular arithmetic (by Product and Inverse Congruence Rules) hence so too is their composition (modular "division" by units = invertibles = integers $B$ coprime to the modulus).

Similarly the Polynomial Congruence Rule extends to polynomial fractions (rational "functions") or to any expression composed of sum, product, and inverse operations (where the inverses all exist) by a simple inductive proof.

See this answer for much further discussion.