# Different numbering style in title and reference for sections

I would like to put the number of my section in a colored box in the title but when I use a reference, I only want the number of the section to be printed and not the colored box...

I used

\renewcommand{\thesection}{\colorbox{blue}{\arabic{section}.}}


and it works for the title but it also put the colored box in the main text when I cite the section with \ref{sec}. Is there a solution to change the numbering of the section independently in the title and the reference?

• (1) Welcome, (2) on this site you should always post a small but full self contained example that others can copy and test. Then we know your setup (document class, packages etc). (3) As you have noticed it is a very bad idea to put formatting into \thesection. Instead you should change how \section is formatted. But without any information about your doc, we cannot help you with that as there are several approaches depending on document class and packages used. – daleif Dec 3 '19 at 14:20
• To add to the previous comment: in many cases what you want to achieve can be accomplished using the titlesec package. If you are just doing this from scratch over one of the standard classes (article, book, etc) I would suggest this approach. – Willie Wong Dec 3 '19 at 14:54

This kind of formatting can be done using the titlesec package. It provides a \titleformat command which allows to format the title of sections or other parts of a document, and without affecting the counter reference commands (like \thesection). See the package documentation for more details.

For the colored boxes around section numbers, the following example should work.

\documentclass{article}
\usepackage{color}
\usepackage{titlesec}
\titleformat{\section}{\Large\bfseries}{\colorbox{blue}{\thesection.}}{1em}{}

\begin{document}

\section{First section}
\label{sec1}

Test paragraph.

\section{Second section}

Test paragraph with reference to section \ref{sec1}.

\end{document}


The following minimal example updates the way the sectional unit number is printed as part of the title, introducing a special formatting mechanism. If no (new) special format is specified (on a per sectional unit basis), it defaults to \csname the#1\endcsname\quad, which is the default under the regular document classes anyway.

\documentclass{article}

\usepackage{xcolor}

\makeatletter
\renewcommand{\@seccntformat}[1]{%
\ifcsname the#1cntformat\endcsname
\csname the#1cntformat\endcsname % Special sectional unit number formatting
\else
\csname the#1\endcsname\quad % Default if no special format exists
\fi
}
\makeatother

\begin{document}

\tableofcontents

\bigskip

See Section~\ref{sec:section}, Subsection~\ref{sec:subsection} or Subsubsection~\ref{sec:subsubsection}.

\section{A section}\label{sec:section}
\subsection{A subsection}\label{sec:subsection}
\subsubsection{A subsubsection}\label{sec:subsubsection}

\end{document}