Tips on aligning HTML divs properly while printing with jQuery using flexbox CSS

Need help with aligning div content for print media query.

Created a media query to target both screen and print.

Print media query is similar to the screen media query.

Display is fine on the screen, but misalignment occurs when trying to print.

Fiddle: https://jsfiddle.net/20dhfoub/7/

Looking for guidance on where I'm going wrong.

//markup

<div id="folha">
        <div class="container-print center">
            <div class="color-black">
                MY TEST
            </div>
            <div class="paciente color-black">
                <div><strong class="ng-binding">THATIANA NUNES ALMEIDA</strong></div>
                <div class="medplano">
                 <div class="ng-binding">Sem Pref</div>
                 <div class="ng-binding">IRB-APOSENTADOS/EX COLABORADORES</div>
                </div>
                <div class="medplano">
                  <div class="ng-binding">15/01/182018 20:46:13</div>
                  <div>TOTEM</div>
                  <div class="ng-binding">Matr:00000</div>
                </div>
            </div>
            <div class="color-black">
                <span style="border-radius:50%; border:solid black 1px;padding:5px">TRAN</span>
                <span style="border-radius:50%; border:solid black 1px;padding:5px">REC</span>
            </div>
        </div>    
        <div class="container-obs color-black">
          <div class="ng-binding"></div>      
          <div class="ng-binding">Rx e Procedimentos no receituário com CID. Fratura podemos cobrar  Consulta.Recepção: Fratura podemos cobrar Consulta.Densitometria óssea com autorização via fax 2240.1621.Procedimentos acima 300 chs, necessita de autorização. Paciente deverá apresentar lâmina de pagamento. Observar sempre validade da carteira.
          </div>      
        </div>    
 </div>

//css

 @media screen {
    #printSection{
        display: none;
    }
   .circle{
     border-radius:50%; 
     border:solid black 1px;
     padding:5px
    }
    .container-obs{
         display: flex;
         flex-direction: column;
    }
    .container-print {
         display: flex;
         padding-top:10px;
    }
    .container-print div:last-child {
      margin-left: auto;
    }
    .center {
     align-items: center;
    }
    .medplano{
         display: flex;
    }
    .medplano>div{
         margin-right: 30px;
    }
    .paciente {
         margin-left: 15px; 
    }
 }
 @media print {
    body * {
      display:none;
    }
    #folha{
      display:none;
    }
   .circle{
    border-radius:50%; 
    border:solid black 1px;
    padding:5px
   }
    #printSection, #printSection * {
        display: block!important;
        -webkit-print-color-adjust: exact;
        printer-colors: exact;
        color-adjust: exact;
    }
    @page { size: auto;  margin: 0mm; }
    .container-obs{
         display: flex;
         flex-direction: column;
    }
    .container-print {
         display: flex;
         padding-top:10px;
    }
    .container-print div:last-child {
      margin-left: auto;
    }
    .center {
     align-items: center;
    }
    .medplano{
         display: flex;
    }
    .medplano>div{
         margin-right: 30px;
    }
    .paciente {
         margin-left: 15px; 
    }
 }

//js

$(function() {
 var PrintDoc=function(id) {
        var printSection = document.getElementById('printSection');
        // if there is no printing section, create one
        if (!printSection) {
            printSection = document.createElement('div');
            printSection.id = 'printSection';
            document.body.appendChild(printSection);
        }
        var elemToPrint = document.getElementById(id);
        if (elemToPrint) {
                    printElement(elemToPrint);
        }
        function printElement(elem) {
            // clones the element you want to print
            var domClone = elem.cloneNode(true);
            printSection.innerHTML = '';
            printSection.appendChild(domClone);
            console.log(printSection.innerHTML)
            window.print();
        }
        if (window.matchMedia) {
                var mediaQueryList = window.matchMedia('print');
                mediaQueryList.addListener(function(mql) {
                    if (!mql.matches) {
                        afterPrint();
                    } else {
                        // before print (currently does nothing)
                    }
                });
            }

        window.onafterprint = afterPrint;
        function afterPrint() {
            // clean the print section before adding new content
               printSection.innerHTML = '';

        }
};
PrintDoc('folha');

});

Answer №1

Here's a simple solution for you. The only change I made was adding a CSS declaration to hide the direct child element body > folha.

 @media print {

    body > #folha{
      display:none;
    }
 }

$(function() {
  var PrintDoc = function(id) {
    var printSection = document.getElementById('printSection');
    // if there is no printing section, create one
    if (!printSection) {
      printSection = document.createElement('div');
      printSection.id = 'printSection';
      document.body.appendChild(printSection);
    }
    var elemToPrint = document.getElementById(id);
    if (elemToPrint) {
      printElement(elemToPrint);
    }

    function printElement(elem) {
      // clones the element you want to print
      var domClone = elem.cloneNode(true);
      printSection.innerHTML = '';
      printSection.appendChild(domClone);
      // console.log(printSection.innerHTML)
      window.print();
    }
    if (window.matchMedia) {
      var mediaQueryList = window.matchMedia('print');
      mediaQueryList.addListener(function(mql) {
        if (!mql.matches) {
          afterPrint();
        } else {
          // before print (currently does nothing)
        }
      });
    }

    window.onafterprint = afterPrint;

    function afterPrint() {
      // clean the print section before adding new content
      printSection.innerHTML = '';
    }
  };
  PrintDoc('folha');

});
@media screen {
  #printSection {
    display: none;
  }
  .container-obs {
    display: flex;
    flex-direction: column;
  }
  .circle {
    border-radius: 50%;
    border: solid black 1px;
    padding: 5px
  }
  .container-print {
    display: flex;
    padding-top: 10px;
  }
  .container-print div:last-child {
    margin-left: auto;
  }
  .center {
    align-items: center;
  }
  .medplano {
    display: flex;
  }
  .medplano>div {
    margin-right: 30px;
  }
  .paciente {
    margin-left: 15px;
  }
}

@media print {
  body>#folha {
    display: none;
  }
  .circle {
    border-radius: 50%;
    border: solid black 1px;
    padding: 5px;
  }
  @page {
    size: auto;
    margin: 0mm;
  }
  .container-obs {
    display: flex;
    flex-direction: column;
  }
  .container-print {
    display: flex;
    padding-top: 10px;
  }
  .container-print div:last-child {
    margin-left: auto;
  }
  .center {
    align-items: center;
  }
  .medplano {
    display: flex;
  }
  .medplano>div {
    margin-right: 30px;
  }
  .paciente {
    margin-left: 15px;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="folha">
  <div class="container-print center">
    <div class="color-black">
      MY TEST
    </div>
    <div class="paciente color-black">
      <div><strong class="ng-binding">THATIANA NUNES ALMEIDA</strong></div>
      <div class="medplano">
        <div class="ng-binding">Sem Pref</div>
        <div class="ng-binding">IRB-APOSENTADOS/EX COLABORADORES</div>
      </div>
      <div class="medplano">
        <div class="ng-binding">15/01/182018 20:46:13</div>
        <div>TOTEM</div>
        <div class="ng-binding">Matr:00000</div>
      </div>
    </div>
    <div class="color-black">
      <span class="circle">TRAN</span>
      <span class="circle">REC</span>
    </div>
  </div>
  <div class="container-obs color-black">
    <div class="ng-binding"></div>
    <div class="ng-binding">Rx e Procedimentos no receituário com CID. Fratura podemos cobrar Consulta.Recepção: Fratura podemos cobrar Consulta.Densitometria óssea com autorização via fax 2240.1621.Procedimentos acima 300 chs, necessita de autorização. Paciente deverá apresentar
      lâmina de pagamento. Observar sempre validade da carteira.
    </div>
  </div>
</div>

Check out this jsfiddle link for more details: https://jsfiddle.net/mkdizajn/20dhfoub/18/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the tweets from the next Twitter user in the Array using blogger.js

I am working on a project that involves a javascript array of Twitter usernames. Using blogger.js, I successfully load the first username along with their last 5 tweets. Now, I am looking to create HTML buttons or links for "previous" and "next" in order ...

Execute an AJAX call in CodeIgniter using jQuery, and when the call is redirected, display the entire page within a

A peculiar issue arises with the form submission process. When the submit button is clicked, jQuery Ajax triggers a call to the controller for form validation. If the validation fails, the form is redrawn; if it passes, the page redirects to the home page ...

table rows are styled with hover effects and alternating colors using CSS

Styles for even and odd table rows are set, but hovering over the table rows is not working. Test it out here: http://jsfiddle.net/w7brN/ CSS style : #table_even tr:hover { background-color:#fffbae!important; } /* hover effect */ #table_even tr:nth-ch ...

Learn the process of triggering an Ajax request by clicking on a Table row

I am facing an issue with my table. Whenever I click on a row, the <TR> element gets assigned the class "selected". My goal is to capture the content of the first <TD> element in that row (which represents an ID), and then make an Ajax request. ...

Having difficulty retrieving the JSON response

var apiurl="https://raw.github.com/currencybot/open-exchange-rates/master/latest.json"; $.ajax( { url:apiurl, type:"POST", dataType:"JSONP", success:function(data) { console.log(data); } }); Attempti ...

What is the best way to choose dynamic content?

This might seem like a trivial question, but it's definitely not (well, at least not to me). I understand that when attempting to attach an event to dynamic content, the .on() method must be used. However, I am faced with the challenge of selecting e ...

Looking to incorporate nested rules in `JSS` using `CSS`?

Can someone guide me on how to use CSS class-nesting in Material-UI or JSS in general? I have been attempting the following: card: { cardHeader:{ marginTop:"30px" } } ...

What is it about the phone screen that makes media content so captivating?

My phone has a resolution of 2280x1080. I noticed that when using the following code, the background color changes to blue on my phone: @media (max-width: 500px) { body { background-color: blue; } } Interestingly, this feature stops working once "compute ...

How to deal with jQuery's set val() behavior on SELECT when there is no matching value

Let's say I have a select box like this: <select id="s" name="s"> <option value="0">-</option> <option value="1">A</option> <option value="2" selected>B</option> <option value="3">C</option> </ ...

Having to click twice in order to close the jQuery dialog box can be frustrating

I've been attempting to set up a div that pops up using jQuery dialog. Initially, when the user clicks on the button and opens the dialog, it closes with the first click. The second time they try to close the dialog, it will reopen the same popup, r ...

Fade out the notification div using jQuery in MVC4

I'm a beginner in the world of JavaScript and JQuery and I could really use some assistance with resolving a simple issue that I've encountered. As part of my application's functionality, I am dynamically loading the following div based on ...

Chosen link fails to update color

I've successfully implemented a navigation bar that changes the content in the body when each link is selected. Utilizing AJAX for dynamic content changing, I can change the color of menu items on hover but am facing issues with changing the color upo ...

Fixed-positioned elements

I'm facing a small issue with HTML5 that I can't seem to figure out. Currently, I have a header image followed by a menu div containing a nav element directly below it. My goal is to make the menu div stay fixed when scrolling down while keeping ...

Efficiently handling multiple form submissions using a single jQuery Ajax request

I'm working on a page that has 3-4 forms within divs, and I want to submit them all with just one script. Additionally, I want to refresh the content of the specific div where the form is located. However, I'm unsure of how to specify the current ...

Setting the default in jQuery and Rails when the document is ready

Currently, I have a set of anchor tags that serve as a filter. I am utilizing jQuery to find the relevant data tag so that when a name is clicked, it will display all the work done by a developer from a list of completed items. To add a touch of elegance, ...

Numerous DIVs with floating elements and border styling

Trying to align two divs with one floating to the left and with a width of 80%, while the other is floated to the left with 20% width, is causing some issues. I want to add a border on the right side of the first div and apply a box-shadow of 5px since eac ...

Is it possible to create a sticky element that stays fixed to the window without using JavaScript?

Using position: sticky has been a game-changer for me. It resolves many issues without the need for JavaScript. However, I've encountered a roadblock. I am trying to create a sticky element that is nested inside multiple <div> elements. Since po ...

Transforming data from a particular csv file and embedding it into an html document

I am currently working on a feature that allows users to select a specific CSV file and display it as an HTML table on the webpage with the click of a button. The process involves: Selecting the desired file from a dropdown menu to determine the CSV fi ...

Locate and dismiss a toast message (Toastr)

I have a webpage where I can add multiple popup notifications called toasts dynamically using the toastr plugin found at https://github.com/CodeSeven/toastr. Each toast has an Ok link that, when clicked, should only close that specific toast and not all v ...

Transferring data from jQuery Ajax to PHP

I'm facing a challenge in retrieving a value back to PHP that I can manipulate and save to the database. It appears that using the GET method with jQuery AJAX is not yielding the desired results. Below is the PHP code snippet where I attempt to captur ...