htmlcsserb

Unordered list alignment and page-break issues


The output is a result of saving/printing as pdf, based on an erb template. The content is dynamicly rendered but maybe I can explain myself with a static example.

I have been running around in circles, playing with block, page-break, list-style-position, without full results.

I'm having trouble making the numbering inline with the title (h2), while making sure that neither the title is split among pages, nor the 1st paragraph is split from the title. I also need for the second line of the title to be aligned right below the numbering. Every time I solve one thing, I mess another one.

I've changed inline, to block, because I read that that might the reason why the page-break was being "ignored", but things still get split.

On my static example, since the paragraphs are listed one by one, I guess that to make sure that the title wouldn't be split from the 1st paragraph, I could add a wrapping div. That's not an ideal solution for me, because on my real code, I have something like this (below), which renders all paragraphs.

 <% point_content.call(key.to_s.delete_suffix('_title'), price_list_variant).each do |paragraph| %>
  <p><%= paragraph %></p>
 <% end %>

Anyway, I tried adding a div there and then the alignments are ruined and also the numbering (everything becomes 0).

Maybe someone has a better idea for this, and understands why this is not working as expected. Thanks in advance.


Solution

  • Something like this:

    function withPageBreak() {
      const titles = document.querySelectorAll("h2");
      titles.forEach(el => el.classList.add("with-page-break"));
      window.print();
      titles.forEach(el => el.classList.remove("with-page-break"));
    }
    h2 {
      display: list-item;
      list-style: inside;
      list-style-type: decimal;
    }
    
    .with-page-break {
      page-break-inside: avoid;
      page-break-after: avoid;
    }
    
    h2::marker {
      color: red;
    }
    
    li {
      display: block;
    }
    
    @page {
      size: 8.5in 5in;
      margin: 1in;
    }
    <button onclick="window.print()">Print without breaks</button>
    <button onclick="withPageBreak()">Print with page breaks</button>
    <ul>
      <li>
        <h2>TITLETITLE TITLETITLE TITLETITLE TITLE TITLE TITLETITLE</h2>
        <p>Paragraph1</p>
        <p>Paragraph1</p>
        <p>Paragraph1</p>
      </li>
      <li>
        <h2>TITLETITLE TITLETITLE TITLETITLE TITLE TITLE TITLETITLE</h2>
        <p>Paragraph1</p>
        <p>Paragraph1</p>
        <p>Paragraph1</p>
      </li>
    </ul>