# Specify width/height of rectangle around text using tikz

I'm attempting to use tikz to draw text with a rectangle of a specified size (the text may or may not fill the specified space). I can get it to draw the text/rectangle at the specified location and I can specify the width of the text (which is good), but the rectangle just auto fits around the size of the text. I'd like to define the draw portion size separate from the text width. The defined size can vary throughout the document, so I can't necessarily define it globally.

\documentclass{article}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
\node[draw,text width=4cm] at (2,-2) {some text spanning three lines with automatic line breaks};
\end{tikzpicture}

\end{document}


You can use minimum width and minimum height keys.

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\node[draw,text width=4cm,minimum height=6cm,minimum width=10cm] at
(2,-2) {some text spanning three lines with automatic line breaks};
\end{tikzpicture}
\end{document}

• That gets me a bit closer, but it seems to ignore the placement (2,-2)? Unless I'm not understanding what that does? – CGRemakes Dec 22 '15 at 16:37
• @CGRemakes (2,2) is not a page coordinate. It doesn't matter where you place it. In the end it clips to the contents of the box. if you want to place relative to a coordinate put a node or something that changes the bounding box. – percusse Dec 22 '15 at 16:40
• Good to know. Is it pretty easy to show an example what you mean? I'm sure it's straight forward, just not familiar with the concept. I've placed graphics and arrows and things using coordinates, but it seems text nodes are a bit different. – CGRemakes Dec 22 '15 at 16:51
• @CGRemakes How do they seem different? They're not. What are you trying to place it relative to? – Torbjørn T. Dec 22 '15 at 17:41
• I'm trying to place them relative to the upper left corner, so more of an absolute position. I do a rectangle using this type of code: \draw[red,fill=red,opacity=0.2] (163.85545954438,-400.62686567164) rectangle (212.53181461115,-410.24194815397); I'm still learning, so I may not understand how the syntax for text works. – CGRemakes Dec 22 '15 at 18:00

You could probably do this by defining a new node style using \tikzset, but macros are easier. Use [inner sep=...] to adjust/increase the size of the node. Otherwise the text will not be centered.

\documentclass{article}
\usepackage{tikz}

\newsavebox{\tempbox}

\newcommand{\textbox}[1]% #1 = text
{\savebox{\tempbox}{#1}% get width
\ifdim\wd\tempbox<4cm\relax
\makebox[4cm]{\usebox{\tempbox}}%
\else
\parbox{4cm}{\raggedright #1}%
\fi}
\begin{document}

\begin{tikzpicture}
\node (A) [draw] at (2,-2) {\textbox{some text spanning three lines with automatic line breaks}};
\node[right=1em,draw] at (A.east) {\textbox{short}};
\end{tikzpicture}

\end{document}