AlbertSamuel
AlbertSamuel

Reputation: 604

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

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.

Upvotes: 3

Views: 1188

Answers (2)

ImprobabilityCast
ImprobabilityCast

Reputation: 464

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>

Upvotes: 2

Maki
Maki

Reputation: 637

Try to put it in a fixed <div>

div.not_fixed {
    border-top: 1px dashed;
    border-bottom: 1px dashed;
    display: flex;
}

div.fixed {
    width: 100px;
    height: 100px;
    border-top: 1px dashed;
    border-bottom: 1px dashed;
    display: flex;
}

.fixed span {
  align-self: flex-end;
}
<div class="not_fixed">
this is a pretty long title
</div>
<BR>
<div class="fixed">
<span>this is a pretty long title</span>
</div>

Upvotes: 0

Related Questions