Home >Web Front-end >CSS Tutorial >Can Letter Spacing in a Div Dynamically Adjust to Fill its Fixed Width?

Can Letter Spacing in a Div Dynamically Adjust to Fill its Fixed Width?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-03 11:52:11242browse

Can Letter Spacing in a Div Dynamically Adjust to Fill its Fixed Width?

Adjusting Letter Spacing to Fit Div Width

Problem:

You have a div with a fixed width, and the text inside the div varies in length. Is it possible to dynamically adjust the spacing between letters in the text so that it always fills the div perfectly, regardless of the text content?

Solution:

The key to achieving this is to combine CSS text-align property and a clever "hack."

CSS Code:

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

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

HTML Code:

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

Explanation:

The "text-align: justify" property aligns the text flush against both left and right margins. The "span" element is a transparent overlay that stretches the width of the div (100%). By placing the "span" after the text content, it forces the text to fill the remaining space, justifying the spacing between the letters.

The above is the detailed content of Can Letter Spacing in a Div Dynamically Adjust to Fill its Fixed Width?. 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