4

This question is based on a previous question: Framing cells vertically in a table

I'd like to frame cells just like that and the answer to the previous question works beautifully – except when the cells are empty, or contain less text at the bottom of the box. See this: enter image description here

Any idea how to fix this? (I've tried different column specifications – doesn't change anything.) How do I tell the tikzmark to mark the rightmost position in any cell, whether empty or filled with text? Any help would be much appreciated.

\documentclass{article}
\usepackage{tikz}
\usepackage{booktabs}
\usetikzlibrary{calc}

\newcommand{\tikzmark}[1]{\tikz[overlay,remember picture] \node (#1) {};}
\newcommand{\DrawBox}[3][]{%
    \tikz[overlay,remember picture]{
    \draw[black,#1]
      ($(#2)+(-0.5em,2.0ex)$) rectangle
      ($(#3)+(0.75em,-0.75ex)$);}
}

\begin{document}
\begin{tabular}{*{7}{c}}\toprule
 Col 1 & Col 2  & Col 3  & Col 4  & Col 5 & Col 6  & Col 7 \\ \cmidrule(lr){2-6}
 0 & 1 & \tikzmark{top left 1}abcd more text & 0 & 0 & 0  & 1 \\
 1 & 0 & www & 0 & 0 & 0 & 1 \\
 0 & 1 & \tikzmark{bottom right 1} & 1 & 0 & 0 & 0 \\
 0 & 0 & 1 & 0 & 0 & 0 & 0 \\
 0 & 0 & 0 & 0 & 0 & 1 & 0 \\
 0 & 0 & 1 & 0 & 0 & 0 & 0 \\
 \bottomrule
  \end{tabular}
\DrawBox[ultra thick, red]{top left 1}{bottom right 1}
\end{document}
kelpie
  • 95

2 Answers2

6

Fill the empty cell:

\documentclass{article}
\usepackage{tikz}
\usepackage{booktabs}
\usetikzlibrary{calc}

\newcommand{\tikzmark}[1]{\tikz[overlay,remember picture] \node (#1) {};}
\newcommand{\DrawBox}[3][]{%
    \tikz[overlay,remember picture]{
    \draw[black,#1]
      ($(#2)+(-0.5em,2.0ex)$) rectangle
      ($(#3)+(0.75em,-0.75ex)$);}
}

\begin{document}
\begin{tabular}{*{7}{c}}\toprule
 Col 1 & Col 2  & Col 3  & Col 4  & Col 5 & Col 6  & Col 7 \\ \cmidrule(lr){2-6}
 0 & 1 & \tikzmark{top left 1}abcd more text & 0 & 0 & 0  & 1 \\
 1 & 0 & www & 0 & 0 & 0 & 1 \\
 0 & 1 & \hspace*{\fill}\tikzmark{bottom right 1} & 1 & 0 & 0 & 0 \\
 0 & 0 & 1 & 0 & 0 & 0 & 0 \\
 0 & 0 & 0 & 0 & 0 & 1 & 0 \\
 0 & 0 & 1 & 0 & 0 & 0 & 0 \\
 \bottomrule
  \end{tabular}
\DrawBox[ultra thick, red]{top left 1}{bottom right 1}
\end{document}

enter image description here

egreg
  • 1,121,712
2

With {NiceTabular} of nicematrix.

\documentclass{article}
\usepackage{nicematrix}
\usepackage{tikz}
\usepackage{booktabs}

\begin{document}

\begin{NiceTabular}{*{7}{c}} \toprule Col 1 & Col 2 & Col 3 & Col 4 & Col 5 & Col 6 & Col 7 \ \cmidrule(lr){2-6} 0 & 1 & \Block[tikz={offset=3pt,draw=red}]{3-1}{} abcd more text & 0 & 0 & 0 & 1 \ 1 & 0 & www & 0 & 0 & 0 & 1 \ 0 & 1 & & 1 & 0 & 0 & 0 \ 0 & 0 & 1 & 0 & 0 & 0 & 0 \ 0 & 0 & 0 & 0 & 0 & 1 & 0 \ 0 & 0 & 1 & 0 & 0 & 0 & 0 \ \bottomrule \end{NiceTabular}

\end{document}

Output of the above code

F. Pantigny
  • 40,250