【问题标题】:How to center-justify the last line of text in CSS?如何将 CSS 中的最后一行文本居中对齐?
【发布时间】:2020-05-08 23:12:03
【问题描述】:

如何使文本居中对齐?

目前, justify 不将最后一行居中。

【问题讨论】:

    标签: html css


    【解决方案1】:

    您可以使用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 的其他值)和 startend 不受支持。

    【讨论】:

    • 对我来说效果很好!谢谢。如果有人想要它“左对齐”,他们可以将最后两个属性更改为左 - 这对我有用!谢谢马克西姆。
    • @NiravZaveri 在这种情况下,您为什么不完全忽略这些属性? text-align: justify 的默认行为不是左对齐最后一行吗?这不是OP询问如何居中的原因吗? :S
    • @underscore_d 现在,我不确定这一点。我什至不记得我这样做是为了什么! :)
    • 请注意,截至 2018 年 7 月,此 still does not work 在 Safari 或 iOS Safari 中。
    • 苹果你好! 2021 年敲门,而我们 40% 的客户使用 iCant。虽然开发人员对 IE 离开开发者的房间感到高兴,但作为交换,Safari 仍然是房间!
    【解决方案2】:

    对于希望获得居中和对齐的文本的人来说,以下方法应该有效:

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

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

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

    这是live demo

    发生了什么事?

    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 将占用所有可用的水平空间,并且您将失去居中效果。

    【讨论】:

    • 比公认的答案好得多,但它不会将短线居中(短于指定宽度的线)。这对于大段落的最后一行很方便,但如果一个段落只包含一行,那就很不方便了。
    • 这是另一个问题的好答案。问题似乎是如何使最后一行居中;这不行。
    【解决方案3】:

    它使用此代码

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

    【讨论】:

    • 请注意,截至 2018 年 7 月,此 still does not work 在 Safari 或 iOS Safari 中。
    • 请注意,截至 2021 年 9 月,这在 Safari 或 iOS Safari 中仍然不起作用。
    【解决方案4】:

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

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

    【讨论】:

      【解决方案5】:
      <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 标记中应用的属性。你只需要对最后一行想要多少单词进行战略性考虑。我已经包含了一个来自小提琴的演示。希望这可以帮助。

      Demo - Center Justify Paragraph Text

      【讨论】:

      • 这是唯一真正的解决方案。使用居中/对齐的文本制作 2 个类,并将两者都应用于您的 div。适用于单/短线。
      • Brownlace:
        无需额外的 CSS 即可完成工作。
      • @cox align 是一个已弃用的属性,不要使用它:w3.org/TR/html4/index/attributes.html
      • 这实际上是一个非常可靠的低技术解决方案。即使在最新的 Chrome 上,新的 moz 语法也不起作用,但确实如此。唯一的问题是,它在最后一行的最后留了一个空格。
      【解决方案6】:

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

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

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

      【讨论】:

      • 查看 Akshay 的回答 - 它适用于响应式布局(在大多数浏览器上)
      【解决方案7】:

      计算文本行的长度并创建一个相同大小的块 作为文本行。使块居中。如果你有两条线,如果它们的长度不同,你将需要两个块。如果您不希望块中有额外的空格,则可以使用 span 标签和 br 标签。 您还可以使用 pre 标签在块内进行格式化。

      你可以这样做: 样式='文本对齐:中心;'

      垂直见: http://www.w3schools.com/cssref/pr_pos_vertical-align.asp

      这里是块和网页布局的最佳方式,去这里学习 2009 年开始的新标准 flex。 http://www.w3.org/TR/2014/WD-css-flexbox-1-20140325/#justify-content-property

      w3schools 也有很多 flex 示例。

      【讨论】:

        【解决方案8】:

        固定宽度的非动态文本的解决方案(不是最好的,但在某些情况下仍然有效)。适用于有一点空间可以将文本“拉伸”到末尾的情况这 倒数第二行。在段落末尾制作一些符号(试验它们的长度)并将其隐藏;应用于段落绝对位置或仅使用填充/边距更正可用空间。

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

        示例(前一段):

        .paragraph {
            width:455px;
            text-align:justify;
        }
        
        .center{
          display:block;
          text-align:center;
          margin-top:-17px;
        }
        &lt;div class="paragraph"&gt;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,&lt;br&gt;&lt;center&gt;vel scelerisque nisl consectetur et.&lt;/center&gt;&lt;/div&gt;

        修复后:

        .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;
        }
        &lt;div class="paragraph"&gt;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, &lt;b&gt;__&lt;/b&gt;&lt;br&gt;&lt;div class="center"&gt;vel scelerisque nisl consectetur et.&lt;/div&gt;&lt;/div&gt;

        【讨论】:

          【解决方案9】:

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

          【讨论】:

            【解决方案10】:

            您也可以通过 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>
            缺点:当页面宽度动态变化时不起作用。

            【讨论】:

              猜你喜欢
              相关资源
              最近更新 更多
              热门标签