92

How can I center-justify text?

Currently, justify does not center the last line.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Voloda2
  • 12,359
  • 18
  • 80
  • 130

10 Answers10

215

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. As of 12.09.2022, Safari 16 supports this feature, as mentioned in the compatibility table.

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

Ozgur O.
  • 97
  • 9
webdif
  • 6,341
  • 3
  • 18
  • 15
  • 1
    Worked out great for me! Thanks. In case someone wants it "left-justified", they can change the last two attributes to left - which is what worked for me! Thanks Maxime. – Nirav Zaveri Apr 16 '14 at 22:55
  • @NiravZaveri Why wouldn't you just leave out the attributes altogether in that case? Isn't the default behaviour for `text-align: justify` to left-align the final line? Isn't that why the OP was asking how to centre it? :S – underscore_d Jul 08 '16 at 21:33
  • @underscore_d Now, I am not sure of this. I don't even remember what I did this for! :) – Nirav Zaveri Oct 18 '16 at 12:21
  • 2
    Note that as of July 2018 this [still does not work](https://caniuse.com/#feat=css-text-align-last) in Safari or iOS Safari. – BadHorsie Jul 31 '18 at 22:40
  • Yo Apple! 2021 is knocking on the door, while 40% of our customers use iCant's.While developers were happy about IE leaving the room of dev- tortures, but in exchange, Safari is still the room! – Stefano Oct 14 '20 at 07:11
  • As of July 2021, still not supported on Safari. – Don Hosek Jun 30 '21 at 17:54
66

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.
Evanesco
  • 897
  • 5
  • 5
  • 8
    Much better than the accepted answer, but it does not centre short lines (lines shorter than the specified width). That's convenient for the last line of a big paragraph but really inconvenient if a paragraph contains only a single line. – Iskar Jarak Mar 24 '13 at 22:14
  • 18
    That's a good answer to a different question. The question seems to be how to center the last line; this doesn't do it. – Clément Dec 31 '14 at 22:56
33

its working with this code

text-align: justify; text-align-last: center;
  • 7
    Note that as of July 2018 this [still does not work](https://caniuse.com/#feat=css-text-align-last) in Safari or iOS Safari. – BadHorsie Jul 31 '18 at 22:41
  • Note that as of September 2021 this still does not work in Safari or iOS Safari. – Apex Sep 09 '21 at 10:54
  • I'll join the party. Note that as of May 2022 this still does not work in Safari or iOS Safari. – avanr May 23 '22 at 16:53
6

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.

thinsoldier
  • 151
  • 2
  • 8
3
<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

Brownlace
  • 47
  • 1
  • 2
  • That's the only real solution. Make 2 classes, with centered / justified text, and apply both to your div. Works for single/short lines to. – cox Apr 15 '13 at 21:30
  • Brownlace:
    do the job without extra css.
    – cox Apr 15 '13 at 21:33
  • @cox align is a deprecated attribute, don't use that: http://www.w3.org/TR/html4/index/attributes.html – FelipeAls Jun 22 '13 at 08:05
  • That's actually a pretty reliable low tech solution. The new moz syntax doesn't work, even on the latest Chrome, but this does. Only problem, it leave a space at the very end of the before-last line. – Draken Jan 28 '15 at 19:16
1

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

maxg
  • 19
  • 1
0

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.

0

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>
Zak the Gear
  • 131
  • 2
  • 14
0

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

Poker Prof
  • 169
  • 5
  • 15
0

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.
Orachigami
  • 416
  • 3
  • 4