# Drawing a simple line with tikz and remove the additonal horizontal space

In the following example I want to draw a simple line with tikz. It seems that the line produced a additional horizontal space left and right about .5\pgflinewidth. I tried outer xsep=0pt but with no result.

\documentclass{scrartcl}
\usepackage{tikz}
\tikzset{linestyle/.style={%
draw=red,%
line width=8ex,
}}%
\begin{document}
\centering
\fboxsep0pt
\fbox{\tikz\draw[use as bounding box,linestyle] (-1,1ex)--(4,1ex);}
\end{document}


How can I avoid the extra space?

-
I couldn't find such a question. –  Marco Daniel Dec 18 '11 at 12:42

The problem comes from how tikz ends a line with the line cap (by default it is the butt type). When a line is thin, this does not change much for the bounding box, but when it is very thick, as in this case, the effect is highly visible. Take a look at the code below and the image, you will see what I mean. I suggest, if all you are looking for is a colored box, to draw a rectangle and fill it.

\documentclass{scrartcl}
\usepackage{tikz}
\tikzset{linestyle/.style={%
draw=red,%
line width=20ex,
}}%
\begin{document}
\centering
\fboxsep0pt
\fbox{
\begin{tikzpicture}
\draw[linestyle,line cap=rect] (-1,0)--(4,0);
\end{tikzpicture}
}

\fbox{
\begin{tikzpicture}
\draw[linestyle,line cap=butt] (-1,0)--(4,0);
\end{tikzpicture}
}

\fbox{
\begin{tikzpicture}
\draw[linestyle,line cap=round] (-1,0)--(4,0);
\end{tikzpicture}
}

\end{document}


-
Thanks for the explanation. Very interesting fact. I need really a line but I will draw it as a rectangle. Thanks. –  Marco Daniel Dec 18 '11 at 13:25
@MarcoDaniel A tiny detail that should be mentioned is that the line is slightly longer now since the line cap is included to the line. –  percusse Dec 18 '11 at 13:37

As a supplement to the neat solution, one can always clip, and there are very nice trim left and trim right tools that can be used for inline pictures particularly:

\documentclass{scrartcl}
\usepackage{tikz}
\tikzset{linestyle/.style={%
draw=red,%
line cap=rect,
line width=16ex,
}}%
\begin{document}
\centering
\fboxsep0pt
\fbox{\tikz{\draw[linestyle](0,1) -- (5,1);}}

\par
\fbox{\tikz[trim left,trim right=5cm]{\draw[line width=16ex,red](0,1) -- (5,1);}}
\end{document}

-