I'm working on a document which is divided into chapters. Each chapter is divided into 4 sections. I would like to create a command that defines a color depending on the number of the section.

I've been trying to do so using ifthen package :

    \ifthenelse{\thesection = 1}{DarkOrange}{%
        \ifthenelse{\thesection = 2}{DeepSkyBlue}{%
            \ifthenelse{\thesection = 3}{MediumSeaGreen}{%

I use titlesec to customize my section titles.

I get the following error :

Use of \@undeclaredcolor doesn't match its definition \section{exploration}

pointing to the line of my first section.

How could I correct this ?

  • 1
    Are you trying to colour the section headings, or make the colour available within the section?
    – Alan Munn
    Aug 10 '14 at 16:06
  • Welcome to TeX.SX! You can have a look at our starter guide to familiarize yourself further with our format.
    – yo'
    Aug 10 '14 at 16:09
  • Do you have in your preamble something like \usepackage[usenames,dvipsnames,svgnames,x11names,table]{xcolor}
    – azetina
    Aug 10 '14 at 16:11

Your code can't work, because the argument of \color must be expandable, which \ifthenelse isn't.

Define four colors with a suffix dependent on the section number:






\section{First is DarkOrange}

\section{Second is DeepSkyBlue}

\section{Third is MediumSeaGreen}

\section{Fourth is DimGray}


enter image description here


Since you're not providing a minimal working example (a complete LaTeX program that is very short yet illustrates the problem you're having) I don't know what your intentions are. But the following works.



    \ifthenelse{\thesection = 1}{\color{DarkOrange}}{%
        \ifthenelse{\thesection = 2}{\color{DeepSkyBlue}}{%
            \ifthenelse{\thesection = 3}{\color{MediumSeaGreen}}{%



{\myColor section 0}




{\myColor \lipsum[3-4]}
  • Your code works well. But if I define a function using myColor : \newcommand{\myFunction}[1]{% {\bfseries{\myColor} #1}} and if I call the function in differents sections, the color used is always the same
    – user60498
    Aug 10 '14 at 16:34
  • Remove the curly brackets around \myColor. They limit the scope of your command.
    – JPi
    Aug 11 '14 at 8:45
  • Thank for your code. But how can we refresh color of each section by chapter?
    – GAVD
    Jun 3 '19 at 7:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.