[Tex/LaTex] How to create a box with caption and label like a float

boxesfloatslabels

I want to create a box (in which I put extra information for the reader) that behaves like a float. In other words, it should have a caption (outside of the box that says Box 1: Here is my box caption) and label that I can refer to with \cref like any other float.

Most of the solutions using \fbox, \framebox, \usepackage{framed} are all creating the box, but not about the caption and the label.

How to accomplish a floating box?

Best Answer

First as a non-float. Then, as a float. EDITED to put caption outside of box. EDITED to introduce new float, InfoBox.

\documentclass{article}
\usepackage{caption,graphicx,newfloat}
\DeclareCaptionType{InfoBox}
\begin{document}
\fboxsep=8pt\relax
\fboxrule=2pt\relax
\begin{center}
\fbox{\centering
  \includegraphics[width=2in]{example-image-A}}\par
  \captionof{InfoBox}{Here is my caption\label{fg:A}}
\end{center}
\begin{InfoBox}[ht]
\centering
\fbox{\centering\medskip
  \includegraphics[width=2in]{example-image-B}}\par
  \caption{Here is my caption\label{fg:B}}  
\end{InfoBox}
In boxes \ref{fg:A} and \ref{fg:B}...
\end{document}

enter image description here