如何在我的框架部分标题中自动换行?

如何在我的框架部分标题中自动换行?

使用以下代码,我得到以下输出:

\documentclass{book}
\usepackage{tikz}
\usepackage{lipsum}
\usepackage[explicit]{titlesec}

\titleformat{\section}[hang]
{\normalfont\Large\bfseries}
{%
\tikz \node[draw=black, fill=black,rounded corners=2,inner sep=2mm]()
{\color{white}\thesection\quad #1};
}{1em}{}

\begin{document}
\chapter{A Test}
\lipsum[2]
\section{A short title}
\lipsum[2]
\section{A very very very very very very very very very very  long title}
\lipsum[2]
\end{document}

在此处输入图片描述

虽然我希望它是这样的:
在此处输入图片描述
我怎样才能做到这一点?

答案1

通过稍微调整代码,可以将章节标题放在\parbox顶部对齐([t]选项)中。框的宽度设置为,\parboxwidth它具有两个定义,具体取决于章节标题的总长度是大于还是小于\textwidth

\ifdim\sectitlewidth>\totalwidth
  \def\parboxwidth{\dimexpr\textwidth-\seclabelwidth-1em-4mm\relax}%
\else
  \def\parboxwidth{\dimexpr\sectitlewidth\relax}%
\fi

\seclabelwith是当前部分标签的长度;1em 是 a 的长度\quad,4mm 等于2*inner sep

平均能量损失

\documentclass{book}
\usepackage{tikz}
\usepackage{lipsum}
\usepackage[explicit]{titlesec}

\newlength{\seclabelwidth}
\newlength{\sectitlewidth}
\newlength{\totalwidth}

\titleformat{\section}[hang]
  {\normalfont\Large\bfseries}
  {\settowidth{\seclabelwidth}{\thesection}%
   \settowidth{\sectitlewidth}{#1}%
   \setlength{\totalwidth}{\dimexpr\textwidth-\seclabelwidth-1em-4mm\relax}%
    \ifdim\sectitlewidth>\totalwidth
      \def\parboxwidth{\totalwidth}%
    \else
      \def\parboxwidth{\sectitlewidth}%
    \fi
    \tikz \node[draw=black, fill=black,rounded corners=2,inner sep=2mm]
      {\color{white}\thesection\quad
        \parbox[t]{\parboxwidth}{#1}};
  }
  {1em}
  {}    

\begin{document}
\chapter{A Test}
\section{A short title}
\lipsum[11]
\section{A not so short title}
\section{A not so short short title}
\section{A very very very very very very long title}
\section{A very very very very very very very very very very  long title}
\lipsum[11]
\end{document}

在此处输入图片描述

编辑一个更简单的版本,使用\titlewidth由 定义的长度titlesec。在此感谢 Bernard:https://tex.stackexchange.com/a/596681/231952

\documentclass{book}
\usepackage{tikz}
\usepackage{lipsum}
\usepackage[explicit]{titlesec}

\newlength{\seclabelwidth}

\titleformat{\section}[hang]
  {\normalfont\Large\bfseries}
  {\settowidth{\seclabelwidth}{\thesection}%
   \settowidth{\titlewidth}{#1}%
    \ifdim\titlewidth>\dimexpr\textwidth-\seclabelwidth-1em-4mm\relax
      \setlength{\titlewidth}{\dimexpr\textwidth-\seclabelwidth-1em-4mm\relax}%
    \fi
    \tikz \node[draw=black, fill=black,rounded corners=2,inner sep=2mm]
      {\color{white}\thesection\quad
        \parbox[t]{\titlewidth}{#1}};
  }
  {1em}
  {}

\begin{document}
\chapter{A Test}
\section{A short title}
\lipsum[11]
\section{A not so short title}
\section{A not so short short title}
\section{A very very very very very veryee long title}
\section{A very very very very very very very very very very  long title}
\lipsum[11]
\end{document}

相关内容