Home > Web Front-end > CSS Tutorial > How to Dynamically Size a DIV to Wrapped Text Content with JavaScript?

How to Dynamically Size a DIV to Wrapped Text Content with JavaScript?

Patricia Arquette
Release: 2024-10-29 20:36:29
Original
1064 people have browsed it

How to Dynamically Size a DIV to Wrapped Text Content with JavaScript?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template