0

I have an application, that takes html as input, renders an image and saves it. It also requires the user to specify the width and height that the image should be. I want to automate the height and width part so the user wouldn't need to set it up manually

The Problem:

if the html is as simple as <p>text</p> the height is pretty easy to find by using clientHeight but the width will be the whole width of the viewport and most of it would be absolutely unneeded to show text, so the picture would be very narrow (height = 16px; width = 1080px) and that is not great.

The Question:

is there any way to find the width of an element that it actually uses? (for instance width required by <p>text</p> would be closer to 16px but not 1080px)

makukas
  • 5
  • 3
  • Could you please be more specific about the tech stack you're using to render it and save? – VPaul Apr 09 '20 at 14:08
  • I have puppeteer set up on aws lambda – makukas Apr 09 '20 at 14:10
  • Does this answer your question? [How do I retrieve an HTML element's actual width and height?](https://stackoverflow.com/questions/294250/how-do-i-retrieve-an-html-elements-actual-width-and-height) – Mark Schultheiss Apr 12 '20 at 15:39

1 Answers1

0

You are having this error because elements such as <p> and <div> will extend the entire width of the parent by default. You should use width: fit-content to stop that.

div {
  background-color: blue;
}

p {
  background-color: red;
}

.width {
  width: fit-content;
}
<div>This is a DIV with width: auto</div>

<p>This is a P with width: auto</p>

<div class="width">This is a DIV with width: fit-content</div>

<p class="width">This is a P with width: fit-content</p>

clientHeight will return the height for the entire window. You should focus on just the parent of the elements you want to render to get a better reading. Use offsetWidth and offsetHeight to get the full width of the parent.

var div = document.getElementById('div');

div.innerHTML = 'Width: ' + div.offsetWidth + '<br>Height: ' + div.offsetHeight;
.square {
  width: 100px;
  height: 100px;
  
  background-color: blue;
}
<div id="div" class="square"></div>
Jack
  • 1,893
  • 1
  • 11
  • 28