Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML-CSS: How to text-align starting from the last word?

Tags:

html

css

I've got quite challenging design to be done. Has anyone ever encounter this?

Here is the design I need, text is bottom aligned, but the text flowing up if there is not enough space on the line.

-------------------


this is 
a pretty long title
-------------------

Here NOT what I need, easily achieved by vertical-align: bottom or position: absolute; bottom: 0, but the text flow is not exactly what I desired.

-------------------


this is a pretty long
title
-------------------

Please notice that the second line has more words than the first line. The wrapping process is if the text is too long for one line, wrap the first word to line above

Any help would be appreciated.

like image 963
AlbertSamuel Avatar asked Nov 27 '25 12:11

AlbertSamuel


1 Answers

This is a horrible mess. But it does do what you want. I don't think there's really any good way to get the behavior you're looking for. Good luck!

window.onload = function () {
    var peaches = document.getElementsByClassName("peaches");
    for (var i = 0; i < peaches.length; i++) {
        addSpans(peaches[i]);
        var box = peaches[i].getBoundingClientRect();
        alignSpans(peaches[i].childNodes, box);
    }
}

function addSpans(element) {
    var text = element.innerHTML.split(" ");
    var result = "";
    for (var i = text.length - 1; i >= 0; i--) {
        result += "<span>" + text[i] + "&nbsp;</span>";
    }
    element.innerHTML = result;
}

function alignSpans(nodes, box) {
    var previousY = null, previousRight = null;

    for (var i = nodes.length - 1; i >= 0; i--) {
        var style = nodes[i].style;
        style.position = "relative";

        var rect = nodes[i].getBoundingClientRect();
        if (previousY != null && rect.y == previousY) {
            style.right = previousRight;
        } else {
            style.right = rect.x - box.x;
            previousY = rect.y;
            previousRight = style.right;
        }
    }
}
p.peaches {
    width: 125px;
    display: flex;
    flex-wrap: wrap-reverse;
    direction: rtl;
    justify-content: flex-end;
}
<body>
<p class="peaches">
this is a pretty long title
</p>
</body>
like image 161
ImprobabilityCast Avatar answered Nov 30 '25 06:11

ImprobabilityCast



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!