tailwind-csshtml2canvas

html2canvas shifting text downwards


I am trying to convert a <div> to an image using html2canvas. However, there's an issue. The text inside the <div> marked with the red circle in Figure 1 has no padding or any kind of offset introducing parameters. But when converted to an image, there's an error gap above the text as shown by the red circle in Figure 2. I have used <h3> (marked with black background) and a <span> (marked with a green background).

Figure 1

Figure 1

Figure 2

Figure 2

Why is it behaving this way and is there a way to fix this ?


Solution

  • Tailwind CSS sets the display property of the img tag to display: block; during preflight. This introduces a line-break below the element which is not seen in the UI render. But, when you convert the same HTML to Image using html2canvas, the line-break gets rendered thus adding an unnecessary space in the resulting image. To solve this, we can add the following code to the tailwind.css file.

    @layer base {
      img {
        @apply inline-block;
      }
    }
    

    The above piece of code should be added after the @tailwind base; line. This solved the issue for me.