如何将 tikz 节点文本垂直居中并水平左对齐

如何将 tikz 节点文本垂直居中并水平左对齐

假设 tikzpicture 由三个节点和节点文本组成。

\documentclass[border=5mm]{standalone}
\usepackage[latin1]{inputenc}
\usepackage{tikz}
\usetikzlibrary{calc, shapes, fit, positioning}

\begin{document}
\tikzset{
    block/.style = {rectangle, draw, rounded corners, text width=6.0cm,
       text depth=1.50cm, text height=0.4cm, line width=0.75pt},
    block_half/.style = {block, text width=2.75cm},
}
    \begin{tikzpicture}[node distance=1.5cm, auto]
        \node [block, anchor=north east] (row0_col1) {
            \textbf{Foo Bar}\\
            \textit{Baz:} Qux
        };
        \node [block_half, right=1cm of row0_col1] (row0_col2) {
            \textbf{Foo Bar}\\
            \textit{Baz:} Qux
        };
        \node [block_half, right=1cm of row0_col2] (row0_col3) {
            \textbf{Foo Bar}\\
            \textit{Baz:} Qux
        };
    \end{tikzpicture}
\end{document}

如何对齐每个节点中的文本,使其垂直居中并水平居左?

答案1

如果您未指定text heighttext depth,则这是默认行为。要使它们都具有相同的高度,请设置minimum height

在此处输入图片描述

\documentclass[border=5mm]{standalone}
\usepackage[latin1]{inputenc}
\usepackage{tikz}
\usetikzlibrary{calc, shapes, fit, positioning}

\begin{document}
\tikzset{
    block/.style = {rectangle, draw, rounded corners, text width=6.0cm,
        line width=0.75pt,minimum height=2.5cm},
    block_half/.style = {block, text width=2.75cm},
}
    \begin{tikzpicture}[node distance=1.5cm, auto]
        \node [block, anchor=north east] (row0_col1) {
            \textbf{Foo Bar}\\
            \textit{Baz:} Qux \\
            \textit{Baz:} Qux \\
            \textit{Baz:} Qux \\
        };
        \node [block_half, right=1cm of row0_col1] (row0_col2) {
            \textbf{Foo Bar}\\
            \textit{Baz:} Qux
            \textit{Baz:} Qux \\
        };
        \node [block_half, right=1cm of row0_col2] (row0_col3) {
            \textbf{Foo Bar}\\
            \textit{Baz:} Qux
        };
    \end{tikzpicture}
\end{document}

答案2

\Centerstack在文本上使用了,并调整了text heighttext depth

\documentclass[border=5mm]{standalone}
\usepackage[latin1]{inputenc}
\usepackage{tikz,stackengine}
\setstackEOL{\\}
\usetikzlibrary{calc, shapes, fit, positioning}

\begin{document}
\tikzset{
    block/.style = {rectangle, draw, rounded corners, text width=6.0cm,
       text depth=.9cm, text height=1.00cm, line width=0.75pt},
    block_half/.style = {block, text width=2.75cm},
}
    \begin{tikzpicture}[node distance=1.5cm, auto]
        \node [block, anchor=north east] (row0_col1) {\Centerstack{%
            \textbf{Foo Bar}\\
            \textit{Baz:} Qux\\
            \textit{Baz:} Qux}
        };
        \node [block_half, right=1cm of row0_col1] (row0_col2) {\Centerstack{%
            \textbf{Foo Bar}\\
            \textit{Baz:} Qux}
        };
        \node [block_half, right=1cm of row0_col2] (row0_col3) {\Centerstack{%
            \textbf{Foo Bar}}
        };
    \end{tikzpicture}
\end{document}

在此处输入图片描述

相关内容