tcolorbox 居中并自动调整为当前文本大小

tcolorbox 居中并自动调整为当前文本大小

考虑以下代码:

\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}

当前输出附在最后。如何修改代码,tcbtab使框自动居中并自动设置为文本的本地文本宽度?(以及如何调整内容“This is a text”前后的垂直空间,因为目前内容在框内没有垂直居中)。

在此处输入图片描述

答案1

框本身与 对齐box align=center,框内的垂直对齐与 完成valign=center,但如果存在top=...以外的其他值0pt,则不会考虑上部框内的顶部跳过。

width=由 中的文本内容调整,在这里,tcbox的包装器tcolorbox似乎是更好的解决方案,因为 总是tcolorbox使用当前的\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}

在此处输入图片描述

相关内容