Html 如何在 CSS 中居中对齐最后一行文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4704896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to center-justify the last line of text in CSS?
提问by Voloda2
How can I center-justify text?
如何将文本居中对齐?
Currently, justify does not center the last line.
目前, justify 不会将最后一行居中。
回答by webdif
You can use the text-align-last
property
您可以使用该text-align-last
物业
.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.
这是一个兼容性表: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.
适用于除 Safari 之外的所有浏览器(Mac 和 iOS),包括 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.
同样在 Internet Explorer 中,仅适用于text-align: justify
(没有其他值text-align
) andstart
和end
不受支持。
回答by Evanesco
For people looking for getting text that is bothcentered 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):
使用以下 CSS 规则(width
根据需要调整属性):
.center-justified {
text-align: justify;
margin: 0 auto;
width: 30em;
}
Here's the live demo.
这是现场演示。
What's going on?
这是怎么回事?
text-align: justify;
makes sure the text fills the full width of thediv
it is enclosed in.margin: 0 auto;
is actually a shorthand for four rules:- The first value is used for the
margin-top
andmargin-bottom
rules. The whole thing therefore meansmargin-top: 0; margin-bottom: 0
, i.e. no margins above or below thediv
. - The second value is used for the
margin-left
andmargin-right
rules. So this rule results inmargin-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
- The first value is used for the
width: 30em;
, which limits the width of thediv
. Only when the width is restricted is there some whitespace left over formargin: auto
to distribute. Without this rule thediv
would take up all available horizontal space, and you'd lose the centering effect.
text-align: justify;
确保文本填充div
它所包含的整个宽度。margin: 0 auto;
实际上是四个规则的简写:- 第一个值用于
margin-top
和margin-bottom
规则。因此margin-top: 0; margin-bottom: 0
,整个事情意味着,即没有高于或低于 的边距div
。 - 第二个值用于
margin-left
和margin-right
规则。所以这个规则导致margin-left: auto; margin-right: auto
. 这是一个聪明的地方:它告诉浏览器利用两侧的任何可用空间并将其均匀分布在左右两侧。结果是居中的文本。
但是,如果没有,这将无法工作
- 第一个值用于
width: 30em;
,它限制了 的宽度div
。只有当宽度受到限制时,才会有一些空白可供margin: auto
分配。如果没有这条规则,div
它将占用所有可用的水平空间,并且您将失去居中效果。
回答by Akshay Vinchurkar
its working with this code
它使用此代码
text-align: justify; text-align-last: center;
回答by thinsoldier
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.
似乎没有办法。您可以通过使用 justify 来伪造它,然后将最后一行文本包裹在一个跨度中并将其设置为文本对齐居中。它适用于小块文本,但对于大量文本或动态文本不是一种有用的方法。
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.
我建议在 Adobe 找一个参与他们 W3C 工作的人,并唠叨他们在下一次会议中提出右/左/中间的理由。如果有人能够推动 CSS 中的基本排版功能,那就是 Adobe。
回答by Brownlace
<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.
我能够通过将内容包装在 div 标签中并应用属性 text-align: center 来实现结果。在 div 标签之后,我立即将内容包装在一个段落标签中并应用了属性 text-align: justify。为了使最后一行居中,我将它从段落标记中排除,然后返回到 div 标记中应用的属性。你只需要战略性地确定最后一行你想要多少个单词。我已经包含了一个来自小提琴的演示。希望这可以帮助。
回答by maxg
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 :(
我认为简而言之,如果您想要任何类型的浏览器/移动响应,这是不可能的:(
回答by Orachigami
You can also split the element into two via HTML + JS.
您还可以通过 HTML + JS 将元素拆分为两个。
HTML:
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:
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
这是一个带有 div 和 p 标签的示例
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>
回答by Poker Prof
Simple. Text-align: justify; (to get the elements aligned) Padding-left: ?px; (to center the elements)
简单的。文本对齐:对齐;(使元素对齐)Padding-left: ?px; (使元素居中)
回答by user4264378
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.
计算文本行的长度并创建一个与文本行大小相同的块。将块居中。如果你有两条线,如果它们的长度不同,你将需要两个块。如果您不希望块中有多余的空格,您可以使用 span 标签和 br 标签。您还可以使用 pre 标记在块内进行格式化。
And you can do this: style='text-align:center;'
你可以这样做:style='text-align:center;'
For vertical see: http://www.w3schools.com/cssref/pr_pos_vertical-align.asp
垂直见: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
这是块和网页布局的最佳方式,去这里学习 flex 于 2009 年开始的新标准 。http://www.w3.org/TR/2014/WD-css-flexbox-1-20140325/#证明内容属性
Also w3schools has lots of flex examples.
w3schools 也有很多 flex 示例。
回答by Zak the Gear
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>