How to center-justify the last line of text in CSS?

HtmlCss

Html Problem Overview


How can I center-justify text?

Currently, justify does not center the last line.

Html Solutions


Solution 1 - Html

You can use the text-align-last property

.center-justified {
    text-align: justify;
    text-align-last: center;
}

Here is a compatibility table : https://developer.mozilla.org/en-US/docs/Web/CSS/text-align-last#Browser_compatibility.

Works in all browsers except for Safari (both Mac and iOS), including Internet Explorer.

Also in Internet Explorer, only works with text-align: justify (no other values of text-align) and start and end are not supported.

Solution 2 - Html

For people looking for getting text that is both centered and justified, the following should work:

<div class="center-justified">...lots and lots of text...</div>

With the following CSS rule (adjust the width property as needed):

.center-justified {
  text-align: justify;
  margin: 0 auto;
  width: 30em;
}

Here's the [live demo][1].

[1]: http://jsfiddle.net/L4pzm/ "Live demo"

What's going on?
  1. text-align: justify; makes sure the text fills the full width of the div it is enclosed in.
  2. margin: 0 auto; is actually a shorthand for four rules:
  • The first value is used for the margin-top and margin-bottom rules. The whole thing therefore means margin-top: 0; margin-bottom: 0, i.e. no margins above or below the div.
  • The second value is used for the margin-left and margin-right rules. So this rule results in margin-left: auto; margin-right: auto. This is the clever bit: it tells the browser to take whatever space is available on the sides and distribute it evenly on left and right. The result is centered text.
    However, this would not work without
  1. width: 30em;, which limits the width of the div. Only when the width is restricted is there some whitespace left over for margin: auto to distribute. Without this rule the div would take up all available horizontal space, and you'd lose the centering effect.

Solution 3 - Html

its working with this code

text-align: justify; text-align-last: center;

Solution 4 - Html

There doesn't appear to be a way. You can fake it by using justify and then wrapping the last line of text in a span and setting just that to text align center. It works ok for small blocks of text but is not a useful approach to large quantities of text or dynamic text.

I suggest finding somebody at Adobe who's involved in their W3C work and nagging them to bring up right/left/center justification in their next meeting. If anyone's gonna be able to push for basic typography features in CSS it'd be Adobe.

Solution 5 - Html

<div class="centered">
<p style="text-align: justify;">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna, vel scelerisque</p>nisl consectetur et.</div>

I was able to achieve the result by wrapping the content in a div tag and applying the attribute text-align: center. Immediately after the div tag I wrapped the content in a paragraph tag and applied attribute, text-align: justify. To make the last line centered, I excluded it from the paragraph tag, which then falls back to attribute applied in the div tag. You just have to strategic about how many words you want on the last line. I've included a demo from fiddle. Hope this helps.

Demo - Center Justify Paragraph Text

Solution 6 - Html

Most of the solutions here don't take into account any kind of responsive text box.

The amount of text on the last line of the paragraph is dictated by the size of the viewers browser, and so it becomes very difficult.

I think in short, if you want any kind of browser/mobile responsiveness, this isn't possible :(

Solution 7 - Html

Calculate the length of your text line and create a block which is the same size as the line of text. Center the block. If you have two lines you will need two blocks if they are different lengths. You could use a span tag and a br tag if you don't want extra spaces from the blocks. You can also use the pre tag to format inside a block.

And you can do this: style='text-align:center;'

For vertical see: http://www.w3schools.com/cssref/pr_pos_vertical-align.asp

Here is the best way for blocks and web page layouts, go here and learn flex the new standard which started in 2009. http://www.w3.org/TR/2014/WD-css-flexbox-1-20140325/#justify-content-property

Also w3schools has lots of flex examples.

Solution 8 - Html

Solution (not the best, but still working for some cases) for non-dinamic text with fixed width.Usefull for situations when there are a little space to "stretch" text to the end of the penultimate line. Make some symbols in the end of the paragraph (experiment with their length) and hide it; apply to the paragraph absolute position or just correct free space with padding/marging.

Good compabitity/crossbrowser way for center-justifying text.

Example (paragraph before):

.paragraph {
    width:455px;
    text-align:justify;
}

.center{
  display:block;
  text-align:center;
  margin-top:-17px;
}

<div class="paragraph">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna,<br><center>vel scelerisque nisl consectetur et.</center></div>

And after the fix:

.paragraph {
    width:455px;
    text-align:justify;
    position:relative;
}
.center{
  display:block;
  text-align:center;
  margin-top:-17px;
}
.paragraph b{
  opacity:0;

-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
filter: alpha(opacity=0);
-moz-opacity: 0;
-khtml-opacity: 0;
}

<div class="paragraph">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna, <b>__</b><br><div class="center">vel scelerisque nisl consectetur et.</div></div>

Solution 9 - Html

Simple. Text-align: justify; (to get the elements aligned) Padding-left: ?px; (to center the elements)

Solution 10 - Html

You can also split the element into two via HTML + JS.

HTML:

<div class='justificator'>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
when an unknown printer took a galley of type and scrambled it to make a 
type specimen book.
</div>

JS:

function justify() {
    // Query for elements search
    let arr = document.querySelectorAll('.justificator');
    for (let current of arr) {
        let oldHeight = current.offsetHeight;
        // Stores cut part
        let buffer = '';
        
        if (current.innerText.lastIndexOf(' ') >= 0) {
            while (current.offsetHeight == oldHeight) {
			    let lastIndex = current.innerText.lastIndexOf(' ');
				buffer = current.innerText.substring(lastIndex) + buffer;
				current.innerText = current.innerText.substring(0, lastIndex);
            }
            let sibling = current.cloneNode(true);
            sibling.innerText = buffer;
            sibling.classList.remove('justificator');
            // Center
            sibling.style['text-align'] = 'center';


            current.style['text-align'] = 'justify';
            // For devices that do support text-align-last
            current.style['text-align-last'] = 'justify';
            // Insert new element after current
            current.parentNode.insertBefore(sibling, current.nextSibling);
        }
    }
}
document.addEventListener("DOMContentLoaded", justify);

Here is an example with div and p tags

function justify() {
    // Query for elements search
    let arr = document.querySelectorAll('.justificator');
    for (let current of arr) {
        let oldHeight = current.offsetHeight;
        // Stores cut part
        let buffer = '';

        if (current.innerText.lastIndexOf(' ') >= 0) {
            while (current.offsetHeight == oldHeight) {
                let lastIndex = current.innerText.lastIndexOf(' ');
                buffer = current.innerText.substring(lastIndex) + buffer;
                current.innerText = current.innerText.substring(0, lastIndex);
            }
            let sibling = current.cloneNode(true);
            sibling.innerText = buffer;
            sibling.classList.remove('justificator');
            // Center
            sibling.style['text-align'] = 'center';
            // For devices that do support text-align-last
            current.style['text-align-last'] = 'justify';
            current.style['text-align'] = 'justify';
            // Insert new element after current
            current.parentNode.insertBefore(sibling, current.nextSibling);
        }
    }
}
justify();

p.justificator {
    margin-bottom: 0px;
}
p.justificator + p {
    margin-top: 0px;
}

<div class='justificator'>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
<p class='justificator'>It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p><p>Some other text</p>

Disadvantage: doesn't work when page width changes dynamically.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVoloda2View Question on Stackoverflow
Solution 1 - HtmlwebdifView Answer on Stackoverflow
Solution 2 - HtmlEvanescoView Answer on Stackoverflow
Solution 3 - HtmlAkshay VinchurkarView Answer on Stackoverflow
Solution 4 - HtmlthinsoldierView Answer on Stackoverflow
Solution 5 - HtmlBrownlaceView Answer on Stackoverflow
Solution 6 - HtmlmaxgView Answer on Stackoverflow
Solution 7 - Htmluser4264378View Answer on Stackoverflow
Solution 8 - HtmlZak the GearView Answer on Stackoverflow
Solution 9 - HtmlPoker ProfView Answer on Stackoverflow
Solution 10 - HtmlOrachigamiView Answer on Stackoverflow