Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

css - Center last line of justified text in Safari and Chrome ("text-align-last" not working)

Hi I am trying to format my web paragraphs so that the text is justified and the last line is centered. I found the CSS property "text-align-last" which allows me to specify the alignment for the last line.

The problem is that this property is not supported by Chrome and Safari (yet...?).

Anyone have an alternative or a trick to do that?

The W3C manual: http://www.w3schools.com/cssref/css3_pr_text-align-last.asp

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't think it's possible in CSS alone.

Here's a JavaScript solution, in which a clone lies behind the element. The element has text-align: justify and the clone has text-align: center.

The code then reduces the height of the original element so that only the clone's last line displays.

var p= document.getElementById('lorem'),
    clone= document.createElement('p');

clone.textContent= p.textContent;
clone.className= 'clone';
p.parentNode.insertBefore(clone, p);
p.style.height= p.offsetHeight - 14 + 'px';
#lorem, .clone {
  position: absolute;
  line-height: 14px;
  font: 14px arial;
  width: 500px;
}

#lorem {
  text-align: justify;
  overflow: hidden;
  background: white;
}

.clone {
  text-align: center;
}
<p id="lorem">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...