If one of the sets is just closed you're plenty of counterexamples to your statement. See the comments. If both sets are compact, we can use something similar to your arguments to prove the result. Just with a bit of careful.
So, consider $X$ a metric space and $A$, $B$ compact subsets of $X$. There exist sequences $\{a_n\}$ in $A$ and $\{b_n\}$ in $B$, such that $\lim_{n\to\infty}d(a_n,b_n)=d(A,B).$ In metric spaces the notion of compactness is equivalent to sequential compactness. Then, since $A$ is compact, there is a subsequence $\{a_{n_k}\}$ such that $\lim_{k\to\infty} a_{n_k}=a\quad\text{ with }\quad a\in A.$ Note that $\lim_{k\to\infty} d(a_{n_k},b_{n_k})=d(A,B).$ Since $B$ is compact, there is a subsequence $\{b_{n_{k_j}}\}$, such that $\lim_{j\to\infty} b_{n_{k_j}}=b\quad\text{ with }\quad b\in B.$ Note that $\lim_{j\to\infty} d(a_{n_{k_j}},b_{n_{k_j}})=d(A,B),$ but, since $d$ is a continuous function$^*$, the above equality says $d(a,b)=d(A,B)\quad\text{ with }\quad a\in A,\, b\in B.$
$^*$ Indeed, consider $d:A\times B\to \mathbb{R}$. By considering the metric $D((a_1,b_1),(a_2,b_2))=d(a_1,a_2)+d(b_1,b_2)$ (just as we needed) in $A\times B$ and the usual metric in $\mathbb{R}$, you can see that $d$ is continuous.
As was pointed out in the comments, you can see that $A\times B$ is compact in $X\times X$ with the metric given above. Since $d$ is continuous in the compact $A\times B$, $d$ attains its extremums. That gives you the desired result.