Home > Web Front-end > CSS Tutorial > 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
Release: 2024-11-23 05:41:16
Original
953 people have browsed it

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;
}
Copy after login
<div>
  Lorem ipsum sit dolor
  <span></span>
</div>
Copy after login

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!

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