Can code a float know which column if a twocolumn document it is set in? I am fine with solutions that only works correctly after a number of recompiles. The code that I want to make dependent on this will not change the size of the box.
- 2,279
1 Answers
This example uses Werner`s answer for a similar problem to identify the column.
UPDATE after follow-up question: asymmetric margins.
% !TeX TS-program = pdflatex
\documentclass[12pt,a4paper,twocolumn]{book}
\usepackage[left=2.00cm, right=4.00cm, top=4.00cm, bottom=3.00cm, marginpar=3cm]{geometry}
\usepackage{showframe}
\usepackage{zref-savepos} % needed <<<<<<<<<<<<<<
\newcounter{columncheck}
\newlength{\ldistance}
\usepackage{kantlipsum}% dummy text <<
\usepackage{graphicx}
%% From https://tex.stackexchange.com/a/543802/161015
\newcommand{\whichcolumn}{%
\hspace*{0.25\textwidth}% center in the column
\setlength{\ldistance}{0.5\paperwidth}
\stepcounter{columncheck}%
\zsaveposx{\thecolumncheck}% \zsaveposx{<label>}
\ifdim\ldistance > \zposx{\thecolumncheck}sp % get stored x pos in sp units
LEFT\else RIGHT\fi
}
\pagestyle{plain}
\begin{document}
1. \kant[1]
\begin{figure}[htp!]
\includegraphics[width=\columnwidth]{example-image-a.jpg}\\
\whichcolumn
\end{figure}
2. \kant[3]
\begin{figure}[tp!]
\includegraphics[width=\columnwidth]{example-image-b.jpg}\\
\whichcolumn
\end{figure}
3. \kant[1-3]
\begin{figure}[htp!]
\includegraphics[width=\columnwidth]{example-image-a.jpg}\\\medskip
\whichcolumn
\end{figure}
\begin{figure}[htp!]
\includegraphics[width=\columnwidth]{example-image-b.jpg}\\
\whichcolumn
\end{figure}
\newpage
\begin{figure}[ht!]
\includegraphics[width=\columnwidth]{example-image-c.jpg}\\
\whichcolumn
\end{figure}
- \kant[1-2]
\end{document}
This code uses
zref's saveposmodule to store the x-coordinate of the center of the column you're placing the command. This x-coordinate is used to identify whether you're in the left/right column, depending on whether it's less than or greater than (or equal> to) 50% of the page area.
- 39,141

\paperwidth, not\pagewidth? – Bubaya Dec 05 '22 at 23:19\paperwidthusing pdflatex. The code was slightly modified to accommodate asymmetrical margins (up to a point!) by using the center of the column instead of its left side as a reference. – Simon Dispa Dec 06 '22 at 12:29