[Tex/LaTex] tcolorbox: Vertically center title box

tcolorboxvertical alignment

I'd like to vertically center the title of a box on the top rule of the box.

Unfortunatley I can't seem to find a way to calculate the height of the title box dopending on the title text and margins.

Is there a good way to do this?

Any advise as much appreciated 🙂


What I tried so far:

In the Quick reference, all lengths that play a role are listed and looking at the code, I also got the values

  • /tcp/titlerule: \kvtcb@title@rule
  • /tcb/toptitle: \kvtcb@toptitle
  • /tcb/bottomtitle: \kvtcb@bottomtitle
  • /tcb/boxsep: \kvtcb@boxsep

Also the Title text seems to be stored in \tcbtitletext.

However, \kvtcb@… doesn't seem to act as lenght, i.e. 0.5\kvtcb… gives an error, and I can only access \tcbtitletext inside the box env.


MWE:

\documentclass{article}

\usepackage{tcolorbox}
\tcbuselibrary{many}
\tcbset{
    enhanced,
    breakable,
    attach boxed title to top left={
        xshift=0.5cm,
        yshift= -3.5mm, % What do I put here? I'd like to have something like:
%       yshift= -0.5\titleboxheight
    },
    top=4mm,
    coltitle=black,
    beforeafter skip=\baselineskip,
}

\newenvironment{mybox}[1]{%
    \begin{tcolorbox}[title={A Box~--~#1}]%
    }{
    \end{tcolorbox}
}

\begin{document}    
    \begin{mybox}{This title box aligned correct}
        Some text.
    \end{mybox}

    \begin{mybox}{This title box is too low}
        Some text.
    \end{mybox}

    \begin{mybox}{\huge This title box is too high}
        Some text.
    \end{mybox}
\end{document}

Produces:

enter image description here

Best Answer

see if yshift=-\tcboxedtitleheight/2 solve your problem (its use is described in 10.2.2 Options for the Boxed Title Placement, tcolorbox documentation, page 159):

\documentclass{article}
\usepackage{tcolorbox}
\tcbuselibrary{many}

\tcbset{
    enhanced,
    breakable,
    attach boxed title to top left={
        xshift=0.5cm,
        yshift=-\tcboxedtitleheight/2},  % <---
    top=4mm,
    coltitle=black,
    beforeafter skip=\baselineskip,
}
\newenvironment{mybox}[1]{%
    \begin{tcolorbox}[title={A Box~--~#1}]%
    }{
    \end{tcolorbox}
    }

\begin{document}
\begin{mybox}{This title box aligned correct}
    Some text.
\end{mybox}

\begin{mybox}{This title box is too low}
    Some text.
\end{mybox}

\begin{mybox}{\huge This title box is too high}
    Some text.
\end{mybox}
\end{document}

enter image description here