How to diagonally divide a table cell … properly?

The tikz solution given in Diagonal lines in table cell by Leo Liu can be fixed by taking into account the width of the node borders (even if those borders are not drawn).

The following MWE gives the right result:

\documentclass[11pt]{article}
\usepackage[T1]{fontenc}
\usepackage{array}
\usepackage{makecell}
\newcolumntype{x}[1]{>{\centering\arraybackslash}p{#1}}
\usepackage{tikz}
\newcommand\diag[4]{%
  \multicolumn{1}{p{#2}|}{\hskip-\tabcolsep
  $\vcenter{\begin{tikzpicture}[baseline=0,anchor=south west,inner sep=#1]
  \path[use as bounding box] (0,0) rectangle (#2+2\tabcolsep,\baselineskip);
  \node[minimum width={#2+2\tabcolsep-\pgflinewidth},
        minimum  height=\baselineskip+\extrarowheight-\pgflinewidth] (box) {};
  \draw[line cap=round] (box.north west) -- (box.south east);
  \node[anchor=south west] at (box.south west) {#3};
  \node[anchor=north east] at (box.north east) {#4};
 \end{tikzpicture}}$\hskip-\tabcolsep}}

\begin{document}
\setlength{\extrarowheight}{0.1cm}
\begin{tabular}{|x{0.5cm}|x{0.5cm}|x{0.5cm}|x{0.5cm}|x{0.5cm}|}\hline
&&&&20\\ \hline
&&&&30\\ \hline
&&&&45\\ \hline
15&12&18&50&\diag{.1em}{.5cm}{$a_i$}{$b_j$}\\ \hline
\end{tabular}
\end{document}

Detail:

Detail


The makecell package uses LaTeX's picture environment for drawing. Rather than use specials, this uses pre-draw graphical elements stored in appropriate fonts. However, such an approach has available only a fixed range of slopes for lines (amongst other limitations). What appears to happen here is that makecell is using the closes height/width it can with this limitation, but that this means that the width may be out by an amount dependent on the different between the actual height/width ratio and the nearest available line slope.

In particular, \diaghead has an optional ratio argument which sets the height-to-width ratios, but this has to be in integer values (try \diaghead(5,-2.5)). Thus the code is not allow us to bypass the fixed ratios available even with more extended picture support (for example the eepic package).

Using TikZ circumvents this problem as the line is then draw as a special, which may be of any angle. (Limitations on specials are down to the driver, not the fonts available). It's also worth noting that TikZ is written assuming floating point values from the start, so correctly handles the calculations.

A number of approaches to the problem are available in Diagonal lines in table cell (see in particular Leo Liu's answer, which uses TikZ only as far as dealing with the split cell). The diagbox package is also available: it uses pict2e to implement the split box.