1

Assumed we have some simple code to display a text node with a colored fill behind the text.


Minimum working example (MWE):

\documentclass[tikz,border=5mm]{standalone}

\begin{document}
    \begin{tikzpicture}
        \draw [fill=red] (0,0) -- (1,0) -- (1,1) -- (0,1) --cycle node [above right, xshift=0.25mm,yshift=2.5mm, fill=white] {Text};
    \end{tikzpicture}
\end{document}

Screenshot of the result:

Screenshot of the result


Description of the issue:

As you can see, there is a lot of white fill space on each side of the text. In some situations this white space is too big in its spatial extent.

How can I decrease the extension of the white fill without loosing text alignment centered? I've tried with text width=XXXX and align=center already, but this does only change the white space on the right side while the text won't be aligned as centered anymore.

How is it possible to decrease the extent of the fill on the left and right side, and maybe even at the top and bottom side?

  • 4
    Hey! I think the white space correspond to the node inner sep! If you set it to 0pt (with the option inner sep=0pt) the node edge (here the white rectangle borders) will be touching the text (in every direction: left, right, top and bottom). By default, this value is not zero and correspond here to the extent of the fill you are talking about! So you might only need to change this value to change the gap between the white rectangle and your text! I hope this will help you! :) – Vinzza Feb 6 at 13:01
2

A more easier approach:

\documentclass[tikz,border=5mm]{standalone}

\begin{document}
    \begin{tikzpicture}
    \node at (0,0) (a) {};
       \draw [fill = red] (-0.5,-0.5) rectangle (0.5,0.5);
        \node[draw = none,fill=white, inner sep = 0pt] at (a.center){Text};
    \end{tikzpicture}
\end{document}

this would give you:

enter image description here

As you draw more complicated diagrams, these type of predefined nodal definitions comes handy.

PS: Thank you @Vinzza for the nice hint!

As @Vinzza already mentioned you can play with inner sep = <size> to adapt the spacing.

1

In case you want a filled node but with text over a white background you can use a node with a centered label instead of a filled path with an independent centered node:

\documentclass[tikz,border=2mm]{standalone} 

\begin{document}
\begin{tikzpicture}
\node[minimum size=2cm, fill=red, label={[fill=white, inner sep=0pt]center:Text}] {};
\end{tikzpicture}
\end{document}

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.