[Tex/LaTex] How to make sure the images properly float on the marginpar

marginpar

I want to create a problem booklet consisting of some questions and images on the marginpar. How to make sure the images properly float on the marginpar?

If you carefully see the left image below, you will notice that the most bottom image gets cropped as it is not properly floated.

enter image description hereenter image description here

\documentclass[twoside,12pt]{book}
\usepackage[
    a4paper,
    vmargin=2cm,
    outermargin=9cm,
    innermargin=2cm,
    marginparwidth=7cm,
    marginparsep=20pt
]{geometry}

\usepackage{graphicx}
\usepackage{marginnote}
\usepackage{caption}
\usepackage{lipsum}

\newcommand\MarginFig[1]{%
\marginpar{\includegraphics[width=\marginparwidth]{example-image-a}
\captionof{figure}{#1}
\label{#1}}}



\begin{document}
\chapter{Higgs Boson}
\lipsum[1-3]

\begin{enumerate}
\item
\MarginFig{1}
\MarginFig{2}
\MarginFig{3}
\lipsum[1-2]

\item
\MarginFig{4}
\MarginFig{5}
\MarginFig{6}
\lipsum[1-2]

\item 
\MarginFig{7}
\MarginFig{8}
\MarginFig{9}
\lipsum[1-2]

\end{enumerate}
\end{document}

This question is a continuation of my previous question.

Edit 3

Bonus questions (without prizes): Among the permutation of
\MarginFig{n}, \MarginFig{n+1}, \MarginFig{n+2}, and \lipsum[1-2], which one will produce the best floating?

Best Answer

The package marginfix will help avoid overflows. It doesn't implement any "intelligent" floating though, so be prepared for margin images to "pile up" if you are using too many of them.

Related Question