[Tex/LaTex] Center table or tikzpicture horizontally ignoring margins

horizontal alignment

How can I center a table or in my case a tikzpicture horizontally ignoring the margins? My tikzpicture is slightly too big causing it not to be centered properly(sticks into the right margin slightly too much but if properly centered it will be less)

I've tried

 \makebox[\textwidth][c]{}

but I just get a bunch of errors.

Best Answer

Add ampersand replacement=\& to the tikzpicture options and change every & in your tikzpicture to \& (See Section 17.5 Considerations Concerning Active Characters of the pgf manual):

\documentclass{article}
\usepackage{lipsum}
\usepackage{tikz}
\usetikzlibrary{matrix}

\begin{document}

\lipsum[2]

\noindent\makebox[\textwidth]{%
\begin{tikzpicture}[ampersand replacement=\&]
\matrix [matrix of nodes]
{
8 \& 1 \& 6 \& 8 \& 1 \& 6 \& 8 \& 1 \& 6 \& 6 \& 8 \& 1 \& 6 \& 6 \& 8 \& 1 \& 6 \& 6 \& 8 \& 1 \& 6 \& 6 \& 8 \& 1 \& 6 \& 6 \& 8 \& 1 \& 6 \& 6 \& 8 \& 1 \& 6 \& 6 \& 8 \& 1 \& 6 \\
};
\end{tikzpicture}%
}

\end{document} 

enter image description here

If you want to have a caption, you can use a minipage and the \captionof command from the caption or capt-of packages (you cannoy use a float inside a \makebox):

\documentclass{article}
\usepackage{caption}
\usepackage{tikz}
\usetikzlibrary{matrix}
\usepackage{lipsum}

\begin{document}

\lipsum[2]

\noindent\makebox[\textwidth]{%
\begin{minipage}{2\textwidth}
\centering
\begin{tikzpicture}[ampersand replacement=\&]
\matrix [matrix of nodes]
{
8 \& 1 \& 6 \& 8 \& 1 \& 6 \& 8 \& 1 \& 6 \& 6 \& 8 \& 1 \& 6 \& 6 \& 8 \& 1 \& 6 \& 6 \& 8 \& 1 \& 6 \& 6 \& 8 \& 1 \& 6 \& 6 \& 8 \& 1 \& 6 \& 6 \& 8 \& 1 \& 6 \& 6 \& 8 \& 1 \& 6 \\
};
\end{tikzpicture}
\captionof{figure}{Test caption}
\end{minipage}%
}

\end{document} 

enter image description here