Home > Web Front-end > CSS Tutorial > How to Dynamically Shrink a DIV to Wrapped Text Using JavaScript?

How to Dynamically Shrink a DIV to Wrapped Text Using JavaScript?

Mary-Kate Olsen
Release: 2024-10-29 10:03:29
Original
954 people have browsed it

How to Dynamically Shrink a DIV to Wrapped Text Using JavaScript?

Dynamically Shrinking 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.

JavaScript Solution

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

This code snippet does the following:

  1. Creates a range that encapsulates the text.
  2. Gets the clientRect of the text.
  3. Sets the width of the DIV to the width of the clientRect.

Example Usage

<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>
Copy after login
<code class="css">p {
  max-width: 250px;
  padding: 10px;
  background-color: #eee;
  border: 1px solid #aaa;
}

#bad {
  background-color: #fbb;
}</code>
Copy after login

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!

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