Home >Web Front-end >CSS Tutorial >How Can I Justify the Last Line of Text in a DIV Across Browsers?

How Can I Justify the Last Line of Text in a DIV Across Browsers?

Susan Sarandon
Susan SarandonOriginal
2024-12-07 06:06:16603browse

How Can I Justify the Last Line of Text in a DIV Across Browsers?

Justifying the Last Line of a DIV

Despite the logical concerns raised in the original query, we can clarify how to text-align: justify the last line in a DIV. Ordinarily, this terminal line often aligns to the left instead of following the text-justification rules.

To address this, we present a comprehensive solution that is compatible across multiple browsers, including IE6 and later versions.

The Cross-Browser Method

This method leverages two key techniques:

text-align-last: justify;: This CSS property is specifically designed to justify the last line of text in a block-level element. However, it is only supported by Internet Explorer.

:after Pseudo-Content with Inline-Block:

This technique employs the :after pseudo-element to insert an invisible inline-block element after the DIV. This element is then styled to have a width of 100%, effectively occupying the entire width of the DIV and forcing text to justify to its full extent.

CSS Implementation

p, h1 {
   text-align: justify;
   text-align-last: justify;
}

p:after, h1:after {
   content: "";
   display: inline-block;
   width: 100%;
}

Handling Single-Line Text

In cases where the DIV contains only one line of text, an additional CSS rule is necessary to prevent an extra blank line from being added by the :after pseudo-element.

h1 {
   text-align: justify;
   text-align-last: justify;
   height: 1em;
   line-height: 1;
}

h1:after {
   content: "";
   display: inline-block;
   width: 100%;
}

Additional Resources

For further details and insights into this technique, refer to:

[Cross-Browser CSS: Justify Last Line Paragraph Text](http://kristinlbradley.wordpress.com/2011/09/15/cross-browser-css-justify-last-line-paragraph-text/)

The above is the detailed content of How Can I Justify the Last Line of Text in a DIV Across Browsers?. 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