9

I'm trying to display two things (a bordered box and a shaded box), both of which stretch across the entire text area - that is, since I have 1cm margins, the box should start 1cm from the left edge of the page and continue until 1cm from the right edge of the page.

Unfortunately it seems to start too far in (~1.5cm) and continue too far to the right (~0.5cm from the edge.) What am I doing wrong?

\documentclass[a4paper,10pt]{report}
\usepackage[portrait,a4paper,margin=1.0cm,headsep=5mm]{geometry}
\usepackage{color}
\begin{document}

\framebox[\textwidth]{test}

\colorbox[gray]{0.85}{
    \parbox{\textwidth}{test}
}

\end{document}

3 Answers3

11

It is an indentation problem. When you start a new paragraph the text (or everything else) is indented by a certain amount specified in \parindent. The solution is to say to LaTeX that doesn't have to indent that line using \noindent:

\documentclass[a4paper,10pt]{report}
\usepackage[portrait,a4paper,margin=1.0cm,headsep=5mm]{geometry}
\usepackage{color}
\begin{document}

\framebox[\textwidth]{test}

\colorbox[gray]{0.85}{
    \parbox{\textwidth}{test}
}
\noindent\framebox[\textwidth]{test}

\noindent\colorbox[gray]{0.85}{
    \parbox{\textwidth}{test}
}

\end{document}

I am not sure but I assume that the \colorbox is larger than \textwidth because of an inner border respect to its content that should be considered when you specify the \parbox width

Spike
  • 6,729
10

for the colorbox case add

 \usepackage{calc}

then

\noindent\colorbox[gray]{0.85}{%
    \parbox{\textwidth - 2 \fboxsep}{test}%
}

The two % are needed otherwise the colorbox consists of a word-space a parbox and another wordspace so its content is 2 spaces wider than the inner box, and then colorbox itself adds padding so you want to make the parbox a bit smaller.

David Carlisle
  • 757,742
3

Remarks

  1. Specifying showframe=true or just showframe as the geometry option will show the \textwidth border. The border will ease you to see whether the contents move beyond it.

    enter image description here

  2. \colorbox does not have a frame but only a padding. You need to adjust the parbox size as \dimexpr\textwidth-2\fboxsep\relax.

  3. \fbox have both padding and frame, then the parbox size becomes \dimexpr\textwidth-2\fboxsep-2\fboxrule\relax.

  4. Use \noindent to remove the paragraph indentation.

  5. \fboxsep controls the padding and \fboxrule controls the frame thickness.

\documentclass{article}
\usepackage[
    paperwidth=7cm,
    paperheight=7cm,
    margin=2cm,
    showframe=true]
{geometry}

\usepackage{xcolor}



\begin{document}
    \noindent
    \colorbox{red}{%
        \parbox{\dimexpr\textwidth-2\fboxsep\relax}
        {\centering test}%
    }

    \noindent
    \fbox{%
        \parbox{\dimexpr\textwidth-2\fboxsep-2\fboxrule\relax}
        {\centering test}%
    }
\end{document}