[Tex/LaTex] Ignore inner sep for tikz bounding box

bounding boxtikz-pgf

Is there a way to have tikz ignore the white space produced by a node's inner sep when calculating the picture's bounding box?

Consider the following MWE:

\documentclass{article}

\usepackage[showframe,pass]{geometry}
\usepackage{tikz}

\begin{document}

\noindent \begin{tikzpicture}
\node[inner sep=0pt] (X) {X};
\draw (X) -- ++ (0.5, 0);
\draw[gray] (current bounding box.south west) rectangle (current bounding box.north east);
\end{tikzpicture}

\noindent X

\noindent \begin{tikzpicture}
\node[inner sep=2pt] (X) {X};
\draw (X) -- ++ (0.5, 0);
\draw[gray] (current bounding box.south west) rectangle (current bounding box.north east);
\end{tikzpicture}

\end{document}

Here's the output:

enter image description here

In this example, the inner sep is useful when drawing lines from/to the node (see the horizontal line in the example), but on the other side, it indents the second X with regard to the normal text. Some way of specifying the bounding box as the smallest rectangle containing all "ink" (and thereby clipping all inner seps and possibly other white spaces that needlessly extend the bounding box) would be great here…

Best Answer

This solution does not really ignore inner sep for bounding box calculation, but might give the desired result in many cases.

It seems that the value of outer sep does not influence the bounding box. So using outer sep instead and setting inner sep = 0 does the trick.

This approach does even work partially for other shapes. In this case a negative inner sep (or inner xsep or inner ysep) may help with quick and dirty fine tuning.

\documentclass[border = 1, varwidth]{standalone}
\usepackage{tikz}
\begin{document}
    \begin{tikzpicture}
        \node[inner sep = 0, outer sep = 0.3333em] (X) {X};
        \foreach \a in {0, 5, ..., 90} \draw (X) -- ++(\a:2em);
        \fill[black, opacity = 0.25] (current bounding box.south west)
                           rectangle (current bounding box.north east);
    \end{tikzpicture}
    \begin{tikzpicture}
        \node[inner sep = 0em, outer sep = 0.3333em, circle] (X) {X};
        \foreach \a in {0, 5, ..., 90} \draw (X) -- ++(\a:2em);
        \fill[black, opacity = 0.25] (current bounding box.south west)
                           rectangle (current bounding box.north east);
    \end{tikzpicture}

    \pgfkeysvalueof{/pgf/inner xsep}
\end{document}

enter image description here

I have printed out the default value for inner sep for reference.

Related Question