5

I would like to define a tcolorbox with an auto counter. The value of the counter will decide some part of the final style of the box. As an example, imagin that the background of the box alternates between blue and red for even or odd boxes.

There are several questions and answers about conditional styles for TiKZ nodes but I don't understand them and don't know how to apply to tcolorbox.

I know I can do it defining two different styles and manually applaying them, like in following code. But I prefer that LaTeX does the work for me.

\documentclass{article}
\usepackage[most]{tcolorbox}
\usepackage{lipsum}

\newtcolorbox[auto counter]{oddbox}{
    colback=red!20,
    title=\thetcbcounter
}

\newtcolorbox[use counter from=oddbox]{evenbox}{
    colback=blue!20,
    title=\thetcbcounter
}


\begin{document}

\begin{oddbox}
\lipsum[2]
\end{oddbox}

\begin{evenbox}
\lipsum[2]
\end{evenbox}

\begin{oddbox}
\lipsum[2]
\end{oddbox}

\end{document}

enter image description here

1 Answer 1

6

With this new pgfkeys key

/utils/if odd={<num expr>}{<key lists if true>}{<key lists if false>}

you can use

/utils/if odd={\value{tcb@cnt@mybox}+1}{colback=red!20}{colback=blue!20}

to get the desired utility.

  • When <options> in \newtcolorbox[...]{mybox}{<options>} are being processed at \begin{mybox}, counter wrappers \tcbcounter and \thetcbcounter are not updated or defined yet, nor the inner counter is stepped. These actions all take place after processing <options>, see below. Thus you have to use the inner counter tcb@cnt@mybox directly and add 1 to its value manually.

    Check use of \tcolorbox[#6,options@for=#3] in \__tcobox_new_tcolorbox:w in tcolorbox.sty v5.1.1 for more info. Here style options@for holds <options> given to \newtcolorbox. This processing order is required by keys like /tcb/void, which acts by overwriting options@for (through options@for/.code=).

  • The key path prefix /utils is for wider range of use in all pgfkeys places, and is not the only option.

    If for example it's defined by \tcbset{if odd/.code n args=...}, then you can use \newtcolorbox[...]{mybox}{if odd={}{}{}} but in non-tcolorbox places you have to use /tcb/if odd to get access to it.

\documentclass{article}
\usepackage{tcolorbox}
\usepackage{lipsum}

\makeatletter
\newtcolorbox[auto counter]{mybox}{
    /utils/if odd={\value{tcb@cnt@mybox}+1}% no spaces in between the three args
      {colback=red!20}{colback=blue!20},
    title=\thetcbcounter
}

\pgfkeys{
  /utils/if odd/.code n args={3}{%
    \ifodd\numexpr#1\relax
      \pgfkeysalso{#2}%
    \else
      \pgfkeysalso{#3}%
    \fi
  }
}

\begin{document}

\begin{mybox} \lipsum[2][1-2] \end{mybox}
\begin{mybox} \lipsum[2][1-2] \end{mybox}
\begin{mybox} \lipsum[2][1-2] \end{mybox}

\end{document}

enter image description here

2

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .