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

后端 未结 1 1656
庸人自扰
庸人自扰 2021-01-18 19:24

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 speci

1条回答
  •  悲&欢浪女
    2021-01-18 20:08

    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;
    }

    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.

    0 讨论(0)
提交回复
热议问题