如何在CSS中居中对齐文本的最后一行?


76

如何使文字居中对齐?

当前,justify不在最后一行的中心。

Answers:


168

您可以使用该text-align-last物业

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

这是一个兼容性表:https : //developer.mozilla.org/en-US/docs/Web/CSS/text-align-last#Browser_compatibility

除Safari(Mac和iOS)之外的所有浏览器包括Internet Explorer )中均可使用

同样在Internet Explorer中,仅适用于text-align: justify(无其他值text-align),start并且end不受支持。


1
对我来说很棒!谢谢。如果有人希望它“左对齐”,则可以将最后两个属性更改为left-这对我有用!谢谢马克西姆。
Nirav Zaveri 2014年

@NiravZaveri在这种情况下,为什么不完全忽略所有属性?text-align: justify左行最后对齐不是默认行为吗?这不是OP为何要问如何居中的原因吗?:S
underscore_d

@underscore_d现在,我不确定。我什至不记得我这样做的目的!:)
Nirav Zaveri

2
请注意,截至2018年7月,此功能仍无法在Safari或iOS Safari中使用。
BadHorsie

哟,苹果!2021年即将来临,而我们40%的客户使用的是iCant。虽然开发人员对IE离开开发室感到满意,但作为交换,Safari仍然是开发室!
斯特凡诺

62

对于希望获得集中又合理的文本的人们,下面的方法应该起作用:

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

使用以下CSS规则(width根据需要调整属性):

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

这是现场演示

这是怎么回事?

  1. text-align: justify;确保文本填满div其中所包含的全部宽度。
  2. margin: 0 auto; 实际上是四个规则的简写:
    • 第一个值用于margin-topmargin-bottom规则。因此整个意思是margin-top: 0; margin-bottom: 0,即没有高于或低于的边距div
    • 第二个值用于margin-leftmargin-right规则。因此,此规则导致margin-left: auto; margin-right: auto。这是一个聪明的地方:它告诉浏览器获取两侧可用的任何空间,然后在左右两侧均匀分配。结果是居中文本。
      但是,如果没有,这将无法工作
  3. width: 30em;,限制了的宽度div。仅当宽度受到限制时,才留有一些空白margin: auto可分配。没有此规则,div它将占据所有可用的水平空间,并且您将失去居中效果。

6
比接受的答案好得多,但是它不会使短线居中(短于指定宽度的线)。这对于大段落的最后一行很方便,但是如果一个段落仅包含一行,那确实很不方便。
Iskar Jarak 2013年

16
这是一个不同问题的好答案。问题似乎是如何使最后一行居中。这没有做到。
2014年


7

似乎没有办法。您可以使用对齐来伪造它,然后将文本的最后一行包裹在一个跨度中并将其设置为文本居中对齐。它适用于较小的文本块,但不适用于大量文本或动态文本。

我建议在Adobe中找一个参与W3C工作的人,并劝他们在下一次会议上提出左右对正的理由。如果有人能够推动CSS的基本排版功能,那就是Adobe。


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>

通过将内容包装在div标记中并应用属性text-align:center,可以实现结果。在div标签之后,我立即将内容包装在一个段落标签中,并应用了text-align:justify属性。为了使最后一行居中,我从段落标签中排除了它,然后将其回退到div标签中应用的属性。您只需要确定最后一行上要多少个单词的策略即可。我包括了小提琴的演示。希望这可以帮助。

演示-居中对齐段落文本


那是唯一真正的解决方案。进行2个班级,使用居中/对齐文本,然后将两个班级都应用到div。适用于单行/短行。
cox

Brownlace:<div align =“ center”>无需额外的CSS即可完成工作。
cox

@cox align是已弃用的属性,请不要使用该属性:w3.org/TR/html4/index/attributes.html
FelipeAls 2013年

这实际上是一个非常可靠的低技术解决方案。即使在最新的Chrome上,新的moz语法也不起作用,但是可以。唯一的问题是,它在最后一行的末尾留有空间。
德拉肯

1

这里的大多数解决方案都没有考虑任何类型的响应文本框。

段落最后一行的文本量取决于查看器浏览器的大小,因此变得非常困难。

简而言之,如果您想要任何类型的浏览器/移动响应能力,那是不可能的:(


见阿克沙伊的答案-它与自适应版式的伟大工程(在大多数浏览器)

0

计算文本行的长度,并创建一个与文本行大小相同的块。将块居中。如果您有两条线,则如果长度不同,则需要两个块。如果您不希望块中有多余的空间,则可以使用span标签和br标签。您也可以使用pre标记在块内格式化。

您可以执行以下操作:style ='text-align:center;'

有关垂直的信息,请参见:http : //www.w3schools.com/cssref/pr_pos_vertical-align.asp

这是块和网页布局的最佳方法,请转到此处学习flex自2009年开始的新标准。 。http://www.w3.org/TR/2014/WD-css-flexbox-1-20140325/#证明内容属性

w3schools也有很多flex示例。


0

解决方案(不是最好的,但在某些情况下仍然可以使用) 固定宽度的非动态文本的文本“拉伸”到倒数第二行末尾的空间很小的情况,请使用full。在段落的末尾添加一些符号(以其长度作为实验)并将其隐藏;适用于段落的绝对位置,或仅使用填充/标记来校正自由空间。

文本居中对齐的良好兼容性/跨浏览器方式。

示例(前面的段落):

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

修复后:

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


0

简单。文字对齐:对齐;(以使元素对齐)左向左填充:?px; (将元素居中)


0

您还可以通过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);

这是带有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 using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.