如何调整块标题的宽度以适应文本的长度

如何调整块标题的宽度以适应文本的长度

我希望块标题宽度能够自动调整到文本的长度。在下面的 MWE 中,我更改了块环境的 beamer 模板,并将块标题的宽度设置为固定值。但是,我希望该值不是固定的,而是调整到标题文本的长度。

\documentclass{beamer} 
\usetheme{Dresden}
\setbeamercolor{block title}{fg=white,bg=blue}
\setbeamercolor{block body}{fg=black,bg=black!5}
\setbeamerfont{block title}{size=\normalsize,series=\bf}
\setbeamerfont{block body}{size=\normalsize}
\setbeamertemplate{block begin}{
    \begin{beamercolorbox}[rounded=true,wd=2cm]{block title}
        \usebeamerfont*{block title}\insertblocktitle
    \end{beamercolorbox}
    \vskip1pt
    \usebeamerfont{block body}
    \begin{beamercolorbox}[wd=1\linewidth,sep=1pt,leftskip=0.2cm,rightskip=0.2cm]{block body}\vskip1pt
}
\setbeamertemplate{block end}{
    \vskip6pt
    \end{beamercolorbox}
}
\begin{document}

\begin{frame}
\begin{block}{Short title}
some text here
\end{block}
\begin{block}{A bit more long title}
some text here
\end{block}
\end{frame}

\end{document}

答案1

您可以使用该tcolorbox包:

\documentclass{beamer} 

\usetheme{Dresden}

\usepackage[most]{tcolorbox}


\setbeamertemplate{block begin}{
    \usebeamercolor[fg]{block body}
    \usebeamercolor[fg]{block title}
    \usebeamercolor[bg]{block body}
    \usebeamercolor[bg]{block title}    
    \begin{tcolorbox}[
      title=\insertblocktitle,
      attach boxed title to top center={yshift=-2mm},
      enhanced,
      colback=structure.fg!75!black!10!,
      colbacktitle=structure.fg!75!black,
      frame empty, 
      ]
}
\setbeamertemplate{block end}{
    \end{tcolorbox}
}
\begin{document}

\begin{frame}
\begin{block}{Short title}
some text here
\end{block}
\begin{block}{A bit more long title}
some text here
\end{block}
\end{frame}

\end{document}

在此处输入图片描述

使用新的 tcolorbox 内部主题可以进一步简化代码 (https://www.ctan.org/pkg/beamertheme-tcolorbox):

\documentclass{beamer} 

\usetheme{Dresden}
\usecolortheme{orchid}

\useinnertheme[rounded]{tcolorbox}

\tcbset{
  attach boxed title to top center={yshift=-2mm},
  enhanced,
  bottom=1mm
}

\begin{document}

\begin{frame}
\begin{block}{Short title}
some text here
\end{block}
\begin{block}{A bit more long title}
some text here
\end{block}
\end{frame}

\end{document}

在此处输入图片描述

相关内容