我目前正在使用以下代码来生成特定样式的章节和子章节。如果能帮助解决以下问题,我将不胜感激:首先,我希望红色章节编号框和蓝色子章节编号框在左边距右对齐(这似乎没有出现在 showframe 中 - 为什么?),而无需临时使用 \hspace 命令(这是我目前能做到的最好的,但并不完美)。其次,我希望包含章节和子章节标题的框延伸到下方文本行的末尾,但不能再远。目前,它似乎超出了范围。我该如何修复?
\documentclass{article}
\usepackage[margin=2.5cm,showframe]{geometry}
\usepackage[explicit]{titlesec}
\usepackage{tikz}
\titleformat{\section}
{\normalfont\Large\bfseries}
{\llap{\tikz[baseline=(a.base)]\node[draw=red!20,fill=white,inner sep=5pt,text height=1.5ex,text depth=-1ex, line width = 2pt](a){\thesection}; \hspace{0.25cm}}}
{0em}
{\tikz[baseline=(a.base)]\node[fill=red!20,inner sep=6pt,text width=\linewidth-4pt,text height=1.5ex,text depth=-1ex, shading=axis,shading angle=0,left color=red!20,right color=white](a){\centering #1};}
\titleformat{\subsection}
{\normalfont\large\bfseries}
{\llap{\tikz[baseline=(a.base)]\node[draw=blue!20,fill=white,inner sep=5pt,text height=1.5ex,text depth=-1ex, line width = 2pt](a){\thesubsection}; \hspace{0.275cm}}}
{0em}
{\tikz[baseline=(a.base)]\node[fill=blue!20,inner sep=6pt,text width=\linewidth-4pt,text height=1.5ex,text depth=-1ex, shading=axis,shading angle=0,left color=blue!20,right color=white](a){\centering #1};}
\begin{document}
\chapter{A chapter}
\section{Introduction}
\subsection{A subsection}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse aliquet magna sed erat tempus, sit amet maximus est tristique.
\end{document}
答案1
使用text width={\linewidth-12pt}
来获取具有适当宽度的节点,因为您需要减去inner sep
6pt 的两倍。另外,最好不要放在命令\hspace
中\tikz
。请注意,负数text depth
在这里不起作用。
\documentclass{article}
\usepackage[margin=2.5cm, showframe]{geometry}
\usepackage[explicit]{titlesec}
\usepackage{tikz}
\titleformat{\section}
{\normalfont\Large\bfseries}
{\hspace*{-0.275cm}\llap{\tikz[baseline=(a.base)]{
\node[draw=red!20, fill=white, inner sep=5pt, text height=1.5ex, text depth=0pt, line width=2pt] (a) {\thesection};
}}}
{0.275cm}
{\tikz[baseline=(a.base)]{
\node[fill=red!20, inner sep=6pt, text width={\linewidth-12pt}, text height=1.5ex, text depth=0pt, shading=axis, shading angle=0, left color=red!20, right color=white] (a) {#1};
}}
\titleformat{\subsection}
{\normalfont\large\bfseries}
{\hspace*{-0.275cm}\llap{\tikz[baseline=(a.base)]{
\node[draw=blue!20, fill=white, inner sep=5pt, text height=1.5ex, text depth=0pt, line width=2pt] (a){\thesubsection};
}}}
{0.275cm}
{\tikz[baseline=(a.base)]{
\node[fill=blue!20, inner sep=6pt, text width={\linewidth-12pt}, text height=1.5ex, text depth=0pt, shading=axis, shading angle=0, left color=blue!20, right color=white] (a) {#1};
}}
\begin{document}
\chapter{A chapter}
\section{Introduction}
\subsection{A subsection}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse aliquet magna sed erat tempus, sit amet maximus est tristique.
\end{document}