5

The output from the following script

\documentclass{article}
\usepackage{tikz}
\usepackage{graphicx}
\begin{document}
\begin{tikzpicture}
  \node(title)[text width = 0.25\textwidth, text height = 3 cm, draw]{title};
  \end{tikzpicture}
\end{document}

is

enter image description here

How can I vertically align the text in the node?

Specifying the text depth as in

\node(title)[text width = 0.25\textwidth, text height = 1cm, text depth = 1 cm, draw]{
    title line 1\\
    title line 2\\
    title line 3};

Does not result in the text being vertically centred.

enter image description here

  • 1
    text height specifies the height of the text, so adds space above the text. You could use text depth to specify a certain depth, which adds space below your text. But I guess you don't want that, either. You're most likely looking for minimum size instead of text height. – Skillmon May 4 '18 at 9:01
  • @Skillmon, could I centre text following your suggestion of using text depth? See my updated question. – Viesturs – Viesturs May 4 '18 at 9:13
  • 2
    No, use minimum size or minimum height, the latter if it's just about vertical dimensions (you already specified horizontal dimensions with text width). – Skillmon May 4 '18 at 9:17
9

text height and text depth specify the vertical dimensions of the text you give explicitly. As a result TikZ thinks the node's text has exactly that height and draws its box like that.

You can use minimum height to set a minimum vertical size of the node, and minimum width for the width (while text width inserts line wrapping at the specified width minimum width does not). The result will be a box in which your text is centred, but the box must have at least those dimensions. Note that minimum height is both height and depth around your text (evenly). If you want line wrapping text which is horizontally centred you can use text width and text centered.

Compare the following:

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[node distance=2cm]
  \node(1)[text centered,text width = 0.25\textwidth, minimum height = 3 cm, draw]
    {title is very long and long};
  \node(2)[minimum width = 0.25\textwidth, minimum height = 3 cm,
    draw,below of=1,anchor=north]{title is very long and long};
  \node(3)[text centered,text width = 0.25\textwidth, text height = 3 cm,
    draw,below of=2,anchor=north]{title is very long and long};
  \node(4)[text centered,text width = 0.25\textwidth, text depth = 3 cm,
    draw,below of=3,anchor=north]{title is very long and long};
  \node(5)[text centered,text width = 0.25\textwidth, text depth = 1.5 cm, text
    height = 1.5cm, draw,below of=4,anchor=north]{title is very long and long};
\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.