2

This article Apply background color in algorithm environment part 2 show how to change the background color of an algorithm, using the package algorithm2e.

I would like to do the same, but only on the code itself so that the caption keeps the page background color.

MNE :

\documentclass{article}
\usepackage[linesnumbered]{algorithm2e}
\usepackage{xcolor}

\SetAlCapSkip{1em}

\begin{document}
\begin{center}
  \colorbox{gray!20}{
    \begin{minipage}{0.8\textwidth}
      \begin{algorithm}[H]
        This is line one\\
        This is line two
        \caption{Some Title.}
    \end{algorithm}
  \end{minipage}}
\end{center}
\end{document}

I obtain:

Result

"Algorithm 1: Some Title" should be with a white background color.

2 Answers 2

4

This is possible, but have to fake the option "ruled" which is by default in the algorithm package and the tag was given below:

    \documentclass{article}
\usepackage[linesnumbered,ruled]{algorithm2e}
\usepackage{framed,xcolor}

\SetAlCapSkip{1em}
\definecolor{shadecolor}{cmyk}{0,0,0,0.15}
\makeatletter
\def\@algocf@pre@ruled{\begin{shaded}}%
\def\@algocf@post@ruled{\end{shaded}\relax}%
\makeatother
\begin{document}

      \begin{algorithm}[H]
        This is line one\\
        This is line two
        \caption{Some Title.}
    \end{algorithm}

\begin{algorithm}
\caption{How to write algorithms}
\SetAlgoLined
\KwData{this text}
\KwResult{how to write algorithm with \LaTeX2e }
initialization\;
\While{not at end of this document}{
read current\;
\eIf{understand}{
go to next section\;
current section becomes this one\;
}{
go back to the beginning of current section\;
}
}
\end{algorithm}


\end{document}
2
  • Note that the command {\algocf@algoframe} after \begin{shaded} seems unnecerssary and produce an unwanted character at the beginning of the algorithm.
    – Vinz
    Jun 20, 2017 at 9:52
  • Please check the modified answer...
    – MadyYuvi
    Jun 20, 2017 at 10:22
0

In the next release 5.3 that is still in beta, I have added two options: shaded and title shaded that allow to shade background of algorithm and background of title. You can get in on my home page

Be aware that this is still in beta and even if these options have been tested, not all interactions possible between options and packages have yet been tested.

1

You must log in to answer this question.

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