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

How can I center-justify text?

Currently, justify does not center the last line.

This question is related to html css

The answer is


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 (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):

_x000D_
_x000D_
.paragraph {_x000D_
    width:455px;_x000D_
    text-align:justify;_x000D_
}_x000D_
_x000D_
.center{_x000D_
  display:block;_x000D_
  text-align:center;_x000D_
  margin-top:-17px;_x000D_
}
_x000D_
<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>
_x000D_
_x000D_
_x000D_

And after the fix:

_x000D_
_x000D_
.paragraph {_x000D_
    width:455px;_x000D_
    text-align:justify;_x000D_
    position:relative;_x000D_
}_x000D_
.center{_x000D_
  display:block;_x000D_
  text-align:center;_x000D_
  margin-top:-17px;_x000D_
}_x000D_
.paragraph b{_x000D_
  opacity:0;_x000D_
_x000D_
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
filter: alpha(opacity=0);_x000D_
-moz-opacity: 0;_x000D_
-khtml-opacity: 0;_x000D_
}
_x000D_
<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>
_x000D_
_x000D_
_x000D_


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


<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


its working with this code

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

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 :(


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.

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
  3. 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.

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.


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

_x000D_
_x000D_
function justify() {_x000D_
    // Query for elements search_x000D_
    let arr = document.querySelectorAll('.justificator');_x000D_
    for (let current of arr) {_x000D_
        let oldHeight = current.offsetHeight;_x000D_
        // Stores cut part_x000D_
        let buffer = '';_x000D_
_x000D_
        if (current.innerText.lastIndexOf(' ') >= 0) {_x000D_
            while (current.offsetHeight == oldHeight) {_x000D_
                let lastIndex = current.innerText.lastIndexOf(' ');_x000D_
                buffer = current.innerText.substring(lastIndex) + buffer;_x000D_
                current.innerText = current.innerText.substring(0, lastIndex);_x000D_
            }_x000D_
            let sibling = current.cloneNode(true);_x000D_
            sibling.innerText = buffer;_x000D_
            sibling.classList.remove('justificator');_x000D_
            // Center_x000D_
            sibling.style['text-align'] = 'center';_x000D_
            // For devices that do support text-align-last_x000D_
            current.style['text-align-last'] = 'justify';_x000D_
            current.style['text-align'] = 'justify';_x000D_
            // Insert new element after current_x000D_
            current.parentNode.insertBefore(sibling, current.nextSibling);_x000D_
        }_x000D_
    }_x000D_
}_x000D_
justify();
_x000D_
p.justificator {_x000D_
    margin-bottom: 0px;_x000D_
}_x000D_
p.justificator + p {_x000D_
    margin-top: 0px;_x000D_
}
_x000D_
<div class='justificator'>_x000D_
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._x000D_
</div>_x000D_
<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._x000D_
</p><p>Some other text</p>
_x000D_
_x000D_
_x000D_ Disadvantage: doesn't work when page width changes dynamically.


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.