使用 titlesec 矩形内部分名称的宽度

使用 titlesec 矩形内部分名称的宽度

我刚刚偶然发现关于花式标题的这个问题。我想知道有没有办法让矩形无论长短都能覆盖部分名称?

\documentclass{article}
\usepackage{titlesec}
\usepackage{tikz}    

\titleformat{\section}[block]{
\LARGE\bfseries\tikz[overlay] \shade[bottom color=gray!20, middle color= gray!10, top color=white] (0,-1ex) rectangle (\textwidth,1em);
}{\thesection}{0.5cm}{}

\begin{document}
\section{section name}
\end{document}

答案1

让我对 Aubrey Blumsohn 的回答进行扩展并稍加修改。

使用 时tcbox width=auto limited,如果达到最大宽度,框将切换为换行。此功能相当新(2015-03-23)。您可能需要更新软件包tcolorbox才能实现此功能。

\documentclass{article}
\usepackage[explicit]{titlesec}
\usepackage{tikz}
\usepackage[skins,breakable]{tcolorbox}

\titleformat{\section}
  {\LARGE\bfseries\selectfont}
  {}{0pt}
  {\tcbox[
      tcbox width=auto limited,% <-----------
      enhanced,
      %boxrule=0pt,
      rightrule=0pt,
      toprule=0pt,
      bottomrule=0pt,
      leftrule=3pt,
      arc=0pt,
      outer arc=0pt,
      left=5pt,
      interior code={\shade[bottom color=gray!20, top color=white] (frame.north west) rectangle (frame.south east);},
    ]{\thesection\hskip0.7em#1}}

\begin{document}
\section{Section name}
\section{Section name longer}
\section{Section name extremely long}
\section{Section name extremely long and longer}
\section{Section name extremely long extremely long extremely long extremely long extremely long extremely long extremely long extremely long extremely long extremely long extremely long extremely long extremely long }
\end{document}

在此处输入图片描述

答案2

Tcolorbox 在这里可能有点过头了,但它通常对灵活的标题很有用。你还没有说如果标题太长,你想要对阴影做什么,所以我就让它超出了页面——两行阴影看起来很糟糕

\documentclass{article}
\usepackage[explicit]{titlesec}
\usepackage{tikz}    
\usepackage[skins,breakable]{tcolorbox}    

\titleformat{\section}
  {\LARGE\bfseries\selectfont}
  {}{0pt}
  {\begin{tcolorbox}[
      enhanced,
      %boxrule=0pt,
      rightrule=0pt,
      toprule=0pt,
      bottomrule=0pt,
      leftrule=3pt,
      arc=0pt,
      outer arc=0pt,
      hbox,
      %breakable,
      left=5pt,
      interior code={\shade[bottom color=gray!20, top color=white] (frame.north west) rectangle (frame.south east);},
    ]\thesection\hskip0.7em#1\end{tcolorbox}}

\begin{document}
\section{Section name}
\section{Section name longer}
\section{Section name extremely long}
\section{Section name extremely long and longer}
\section{Section name extremely long extremely long extremely long extremely long extremely long extremely long extremely long extremely long extremely long extremely long extremely long extremely long extremely long }
\end{document}

在此处输入图片描述

相关内容