Home  >  Article  >  Web Front-end  >  How Can I Stretch Text to Fill a Div\'s Width Using CSS?

How Can I Stretch Text to Fill a Div\'s Width Using CSS?

Barbara Streisand
Barbara StreisandOriginal
2024-11-23 05:41:16891browse

How Can I Stretch Text to Fill a Div's Width Using CSS?

Stretching Text to Occupy Div Width

In a situation where your div maintains a consistent breadth but can contain variable amounts of text, the challenge arises: how to distribute letter spacing to optimally fill the div?

Fortunately, this feat is possible through a strategic combination of CSS properties and a clever hack.

Solution:

  1. Apply text-align:justify; to the div: This ensures the text aligns evenly on both the left and right sides of the allocated space.
  2. Incorporate a span element: Implement a span tag alongside the div and set its width to 100% and height to 1em using inline-block display. This will serve as a "spacer" at the bottom of the text.

Example Code:

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

span {
  background-color: red;
  width: 100%;
  height: 1em;
  display: inline-block;
}
<div>
  Lorem ipsum sit dolor
  <span></span>
</div>

This strategy compels the text to expand across the div's width while preserving letter spacing, creating a visually balanced effect.

The above is the detailed content of How Can I Stretch Text to Fill 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