1

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.

Bubaya
  • 2,279

1 Answers1

3

This example uses Werner`s answer for a similar problem to identify the column.

UPDATE after follow-up question: asymmetric margins.

b

% !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}

  1. \kant[1-2]

\end{document}

This code uses zref's savepos module 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.

Simon Dispa
  • 39,141
  • Are you sure that works? I can't compile that (pdflatex or xelatex from texlive 2022). See https://pastebin.com/QcEpc1M7 for my log file. EDIT: probably should be \paperwidth, not \pagewidth? – Bubaya Dec 05 '22 at 23:19
  • With that change it works, but often produces wrong results. – Bubaya Dec 05 '22 at 23:35
  • Okay, the second is not your fault, but due to my asymmetric margins. Sorry for that. But maybe interesting for others. – Bubaya Dec 05 '22 at 23:46
  • @Bubaya Thank you for your feedback!. You are right, it requires \paperwidth using 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
  • Great, thank you! Made my code much simpler. – Bubaya Dec 06 '22 at 16:49