Home >Web Front-end >CSS Tutorial >How Can I Dynamically Resize Text to Fit a Div\'s Width Using CSS?

How Can I Dynamically Resize Text to Fit a Div\'s Width Using CSS?

Susan Sarandon
Susan SarandonOriginal
2024-11-23 15:22:21856browse

How Can I Dynamically Resize Text to Fit a Div's Width Using CSS?

Resizing Text to Fit Div Width Dynamically

In scenarios where div width remains static while the text content is variable, aligning the text to justify might not suffice. Achieving a perfect fit requires adjusting letter spacing.

CSS Solution with a Trick

To accomplish this, utilize the combination of text-align:justify and a clever hack:

CSS:

div {
  background-color: gold;
  text-align: justify;
}

span {
  background-color: red;
  width: 100%;
  height: 1em;
  display: inline-block;
}

HTML:

<div>
  Lorem ipsum sit dolor
  <span></span>
</div>

Explanation:

  • Set the text alignment to justify using text-align:justify.
  • Insert a span element within the div.
  • Style the span with background color (visible for demonstration), 100% width, 1em height, and inline-block display.
  • By setting the span width to 100% and making it transparent, it acts as a container that expands to fill the remaining space in the div.

The above is the detailed content of How Can I Dynamically Resize Text to Fit a Div\'s Width Using CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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