\subsection accepts \colorbox in argument but \section does not

color

The following mwe which includes \subsection{\colorbox{green}{Subtitle}}
does not work when %\section{\colorbox{green}{Title}} is uncommented.

    \documentclass[11pt]{book}
        \usepackage[usenames,dvipsnames]{xcolor}    
    \begin{document}
    %\section{\colorbox{green}{Title}}
    \subsection{\colorbox{green}{Subtitle}}
    \end{document}

The error seems to be due to the fact that LaTeX reads GREEN instead of green.

Best Answer

Try like this:

\documentclass[11pt]{book}
        \usepackage[usenames,dvipsnames]{xcolor}    
    \begin{document}
    \section[Title]{\colorbox{green}{Title}}
    \subsection{\colorbox{green}{Subtitle}}
    \end{document}

The problem is created by adding the colorbox inside the bookmarks and the TOC and the header...

EDIT For colorbox in TOC:

\documentclass[11pt]{book}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage[pdfpagelabels]{hyperref}
        

        
\let\oldsection\section
\makeatletter
\def\section{%
\@ifstar{\@Starred}{\@nonStarred}%
}
\def\@Starred{%
\@ifnextchar[%
{\GenericWarning{}{Warning: A starred section can not have optional parameters. I am going to ignore them!}\@StarredWith}%
{\@StarredWithout}%
}      
\def\@StarredWith[#1]#2{%
\oldsection*{#2}%
}
\def\@StarredWithout#1{
\oldsection*{#1}%
}
\def\@nonStarred{%
\@ifnextchar[%
{\@nonStarredWith}%
{\@nonStarredWithout}%
}
\def\@nonStarredWith[#1]#2{%
\let\oldaddcontentsline\addcontentsline%
\def\addcontentsline##1##2##3{\oldaddcontentsline{toc}{##2}{\protect\texorpdfstring{\numberline{\thesection}#2}{##3}}}%
\oldsection[#1]{#2}%
\let\addcontentsline\oldaddcontentsline%
}
\def\@nonStarredWithout#1{%
\oldsection{#1}%
}
\makeatother
        
        
\begin{document}
    
    \tableofcontents
    
    \newpage
    \section[Title]{\colorbox{green}{Title}}
    \newpage
    \section[Title2]{\colorbox{green}{Title2}}
    \subsection[Subtitle]{\colorbox{green}{Subtitle}}
\end{document}