Achieving Dynamic DIV Sizing for Wrapped Text Using JavaScript
Shrinking a DIV to the extent of wrapped text content using CSS alone poses a challenge. However, JavaScript can be employed to overcome this limitation and achieve the desired behavior.
In the provided code example, the DIV element ("shrunken") with a max-width of 130px exhibits unwanted margins due to text wrapping. To address this issue, JavaScript is leveraged to calculate the actual width of the wrapped content and adjust the DIV size accordingly.
<code class="js">const range = document.createRange(); const text = p.childNodes[0]; range.setStartBefore(text); range.setEndAfter(text); const clientRect = range.getBoundingClientRect(); p.style.width = `${clientRect.width}px`;</code>
This code snippet utilizes the createRange() function to define a range that encompasses the wrapped text. Then, getBoundingClientRect() calculates the bounding rectangle for the defined range, effectively determining the width of the text content. Finally, the DIV's width is dynamically set to match this width, resulting in a snug fit around the wrapped text.
The above is the detailed content of How to Dynamically Size a DIV to Wrapped Text Content with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!