[Tex/LaTex] A tcolorbox centered and automatically adjusted to the current text size

horizontal alignmentlengthstcolorboxvertical alignmentwidth

Consider the following code:

\documentclass[a4paper, 10pt]{article}
\usepackage[margin=2cm]{geometry}
\usepackage[listings,skins,theorems,breakable]{tcolorbox}
\usepackage{lipsum}
\usepackage{fancyhdr}
\usepackage{tabularx}
\usepackage{xcolor}
\usepackage{multicol}

\newtcbox{\tcbtab}[1]{
    enhanced,
    arc = 0pt,
    outer arc = 0pt,
    titlerule = 0pt,
    boxsep = 0pt,
    left = 0pt,
    right = 0pt,
    width = 0pt,
    colframe = black,
    attach boxed title to top={xshift=0mm,yshift=0mm},
    boxed title style={
    enhanced,
    colback = black,
    arc=0pt,
    outer arc=0pt,
    },
    listing only,
    title = {\centering\makebox[\linewidth][c]{#1}},
}

\begin{document}
\lipsum[1]
\begin{center}
\tcbtab{Title}{
This is a text
}
\end{center}
\lipsum[1]
\begin{multicols}{2}
\lipsum[1]
\begin{center}
\tcbtab{Title}{
This is a text
}
\end{center}
\lipsum[1-2]
\end{multicols}
\end{document}

The current output it attached at the end. How to modify the code of tcbtab such that the box is automatically centered and is automatically set to the local textwidth of the text? (and also how to adjust the vertical space before and after the content "This is a text", because for now the content is not vertically centered inside the box).

enter image description here

Best Answer

The box itself is aligned with box align=center, vertical alignment within the box is done with valign=center, but if there is some top=... value other than 0pt, this top skip inside the upper box is not taken into account.

The width= is adjusted by the text content in tcbox, a wrapper around a tcolorbox seems to be better solution here, since the tcolorbox always use the current \linewidth.

\documentclass[a4paper, 10pt]{article}
\usepackage[margin=2cm]{geometry}
\usepackage[listings,skins,theorems,breakable,most]{tcolorbox}
\usepackage{lipsum}
\usepackage{fancyhdr}
\usepackage{tabularx}
\usepackage{xcolor}
\usepackage{multicol}


\NewDocumentCommand{\tcbtab}{O{}m+m}{%
  \begin{tcolorbox}[%
    enhanced,
    arc = 0pt,
    outer arc = 0pt,
    titlerule = 0pt,
    boxsep = 0pt,
    left = 0pt,
    right = 0pt,
    top=0pt,
    colframe = black,
    box align=center,
    halign=center,
    valign=center,
    attach boxed title to top={xshift=0mm,yshift=0mm},
    boxed title style={
    enhanced,
    colback = black,
    arc=0pt,
    outer arc=0pt,
    },
    listing only,
    title = {\centering\makebox[\linewidth][c]{#2}},#1]
    #3%
    \end{tcolorbox}%
}

\begin{document}
\lipsum[1]
\begin{center}
\tcbtab{Title}{%
This is a text%
}
\end{center}
\lipsum[1]
\begin{multicols}{2}
\lipsum[1]
\begin{center}
\tcbtab{Title}{%
  This is a text and some more text%
}
\end{center}
\lipsum[1-2]
\end{multicols}
\end{document}

enter image description here

Related Question