[Tex/LaTex] Change background color for only a section of the page

backgrounds

I understand one can easily change the background color for text portion easily, but I would like to do the same for an entire portion of the page. How does one change background color for only a section of the page?

Best Answer

The following example uses this approach:

  • Mark or save the top and bottom positions of the band you want to highlight using zref's savepos module (via \zsaveposy{<label>});

  • Insert content into the BackGround of the current page only using eso-pic's \AddToShipoutPictureBG*;

  • That content is a rectangle based on \rule[<raise>]{<width>}{<height>}.

enter image description here

\documentclass{article}

\usepackage{zref-savepos,eso-pic,xcolor}
\usepackage{lipsum}

\begin{document}

\lipsum[1]

\AddToShipoutPictureBG*{% Add the following in the background of the current page only
  \AtPageLowerLeft{% Starting from the lower left corner of the page
    \color{blue!30!white}% Colour content this colour
    \rule% Insert a rule (technically a filled rectangle)...
      [\dimexpr\zposy{bottom}sp-.3\baselineskip]% ...raised to the "bottom" marker
      {\paperwidth}% ...stretching across the entire page
      {\dimexpr\zposy{top}sp-\zposy{bottom}sp}% ...with height "top"-"bottom"
  }%
}%
\zsaveposy{top}%
\lipsum*[2]%
\zsaveposy{bottom}%

\lipsum[3]

\end{document}

Since \zsaveposy uses the \label-\ref system, you'll have to compile at least twice with every change in the vertical position of top and/or bottom.


You can automate the process into an environment colourband:

enter image description here

\documentclass{article}

\usepackage{zref-savepos,eso-pic,xcolor}
\usepackage{lipsum}

%\usepackage{xparse}% Only if you're running LaTeX older than 2020-10
\newcounter{colourband}%
\NewDocumentEnvironment{colourband}{m}{%
  \stepcounter{colourband}% New band
  \leavevmode\zsaveposy{top-\thecolourband}% Start new paragraph and save y-position of top
  \ignorespaces
}{%
  \unskip
  \zsaveposy{bottom-\thecolourband}% Save y-position of bottom
  % Add colour band to BackGround of current page only
  \edef\x{\noexpand\AddToShipoutPictureBG*{%
    \noexpand\AtPageLowerLeft{% Starting from the lower left corner of the page
      \noexpand\color{#1}% Colour content this colour
      \noexpand\rule% Insert a rule (technically a filled rectangle)...
        [\dimexpr\zposy{bottom-\thecolourband}sp-.3\baselineskip]% ...raised to the "bottom" marker
        {\paperwidth}% ...stretching across the entire page
        {\dimexpr\zposy{top-\thecolourband}sp-\zposy{bottom-\thecolourband}sp+\baselineskip}% ...with height "top"-"bottom"
    }%
  }}\x%
}

\begin{document}

\lipsum[1]

\begin{colourband}{blue!20!white}
\lipsum*[2]%
\end{colourband}%

\begin{colourband}{green!15!white}
\lipsum*[3]
\end{colourband}

\end{document}