Home >Web Front-end >CSS Tutorial >How to Dynamically Shrink a DIV to Wrapped Text Using JavaScript?
Shrinking a DIV to accommodate text is typically straightforward. However, when the text wraps to multiple lines due to a maximum width constraint, the DIV fails to shrink accordingly. This can create unsightly margins on the right-hand side of the DIV.
Since a pure CSS solution is not feasible, we turn to JavaScript for a dynamic approach. The following code snippet illustrates how:
<code class="javascript">const range = document.createRange(); const p = document.getElementById('good'); 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 does the following:
<code class="html"><p id="bad">This box has a max width but also_too_much_padding.</p> <p id="good">This box has a max width and the_right_amount_of_padding.</p></code>
<code class="css">p { max-width: 250px; padding: 10px; background-color: #eee; border: 1px solid #aaa; } #bad { background-color: #fbb; }</code>
This example creates two boxes with different padding. The first box demonstrates the original problem, while the second box uses the JavaScript solution to dynamically shrink to the text's width.
The above is the detailed content of How to Dynamically Shrink a DIV to Wrapped Text Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!