Search code examples
htmlcssletter-spacing

how to justify text in multiple links vertically


I need all the links below to be justified vertically, i.e. on left and right side.
font-size should be as is.
Obviously the only way is to adjust letter-spacing, but is it possible to do this automatically for all links inside .wrap.

a{display:block; text-decoration:none;}
.a1{font-size:0.7rem;}
.a2{font-size:1rem;}
.a3{font-size:1rem;}
.a4{font-size:0.7rem;}
<div class='wrap'>
<a href='index.php' class='a1'>LOREM IPSUM</a>
<a href='index.php' class='a2'>DOLOR SIT</a>
<a href='index.php' class='a3'>BLUE SKY</a>
<a href='index.php' class='a4'>DEEP OCEAN</a>
</div>


Solution

  • This is what I came up with. A bit "dirty" but it does exactly what you want. You may find ways to inprove the code as mine runs the same loop twice but I wrote this quickly. At least you'll get an idea.

    First, set the display of a tags to inline-block to be able to measure the largest width of all. Once you have that maxWidth, loop through all elements, wrap each character in a span, and set the display of a tags to flex.

    CSS:

    a{
      display: inline-block;
      width: auto;
      justify-content: space-between;
      text-decoration:none;
      clear: both;
    }
    a.flex{
      display: -webkit-flex;
      display: -ms-flexbox;
      display: flex;
    }
    .a1{font-size:0.7rem;}
    .a2{font-size:1rem;}
    .a3{font-size:1rem;}
    .a4{font-size:0.7rem;}
    a span{
      display:inline-block;
    }
    

    JS:

    var elements = document.querySelectorAll(".wrap > a");
     var maxWidth = 0;
     for (var i = elements.length - 1; i >= 0; i--) {
        maxWidth = Math.max(maxWidth, elements[i].offsetWidth);
     }
     for (var i = elements.length - 1; i >= 0; i--) {
        elements[i].classList.add("flex");
        elements[i].style.width = maxWidth+ "px";
        var text = elements[i].textContent;
        text.split("");
        elements[i].innerHTML = "";
        for (var j = 0; j < text.length; j++) {
           var span = document.createElement("span");
           // Fix: issue reported by Chris L
           // Replace space with non-breaking space HTML code
           span.innerHTML = (text[j] === " ")? "&nbsp;" : text[j];
           elements[i].appendChild(span);
        }
     }
    

    Working example here: https://jsfiddle.net/nLdx923c/