loading...
Cover image for Avoiding Awkward Element Breaks in Print HTML

Avoiding Awkward Element Breaks in Print HTML

amruthpillai profile image Amruth Pillai ・2 min read

As some of you might have seen on my previous post here on DEV.to, I've been working hard on a Resume Builder web app.

You can read more about it here.

Anyway, I'm not here to plug the app. I wanted to share something that I learned recently in the process of building the app. When dealing with resumes, you're going to have people print the page a lot, so the app needs to handle all cases of print. And that's a whole side of CSS that I was not aware of before.

TL;DR

div {
  page-break-inside: avoid;
}

Let's get back to the development process... For example, without any styles related to print, this is how it looks when I hit Cmd + P:

Image

It shows the sidebars too and the entire app. The margins are all off and it's just a mess. Thankfully, CSS helps us here. This is what I used to make it look a bit neater:

@page {
  size: A4;
  margin: 2.5em;
}

@media print {
  html,
  body,
  body * {
    -webkit-print-color-adjust: exact;
    color-adjust: exact;
    visibility: hidden;
  }

  #page,
  #page * {
    visibility: visible;
  }

  #page {
    background-color: white;
    margin: 0;
    padding: 0;
    box-shadow: none;
    position: absolute;
    left: 0;
    top: 0;
  }
}

Now it looked great, but there was still one problem. See if you can guess?

Image

Yep, ugly page breaks that I do not want on my resume or any website for that matter. You never know when someone is going to print your DEV.to article and pass it around the office!

So, how do I fix this issue?

Well, for those who read the TL;DR, that's how. page-break-inside: avoid; can avoid you loads of trouble during print. And this is how I used it within my #page body:

#page,
#page * {
  page-break-inside: avoid;
  visibility: visible;
}

And now, voila... doesn't this look much better?

Image

Basically, the page-break-inside property sets whether a page-break should be avoided inside a specified element. I've applied it to all the elements inside the resume, so nothing gets cut off.

Hope this neat little tip helps you in your development as well :)

Posted on by:

amruthpillai profile

Amruth Pillai

@amruthpillai

Designer and Developer. The very last of my kind. I belong both on Dribbble and GitHub.

Discussion

markdown guide
 

Nobody gives print.css enough love. Thank you for this!

 

True. There's nothing greater than the feeling of printing a website. It makes web developers live and breathe on the browser, the phone and on physical paper.