Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align text like a trapezoid?

Here is the sample html code

<div style="width:100px;height:100px">
    12345 1234 1234 1234 123 12345 1234 1234 123 1234 12345
</div>

And I want the effect like this:

12345 1234 1234
1234 1234 123
12345 1234
1234 1234
123 1234
12345

or

12345
123 1234
1234 1234
12345 1234
1234 1234 123
12345 1234 1234

or

12345 1234 12345
 1234 1234 235
  12345 123 1234
   1234 123 212
    123 1234 12
     1234 12345

I have tried using text-align but the result is not my expected.

How can I do this effect without adding many of <br> and $nbsp, or adding many of <div style="margin..."> by hard code?

Thanks.

like image 981
Steve Lee Avatar asked Dec 26 '22 11:12

Steve Lee


2 Answers

How can I do this effect without adding many of <br> and &nbsp, or adding many of <div style="margin..."> by hard code?

You can't. Same goes for heart-shaped, giraffe-shaped, etc. DOM elements are pretty much rectangular.

You'l have to do something like using Javscript. You weren't very specific on the requirements (monospace font, keeping words together, etc.), but here is one example.

<div id="trapezoid" style="width:100px;height:100px"></div>

<script>
    var data = '12345 1234 1234 1234 123 12345 1234 1234 123 1234 12345';
    var lines = [];
    data.split(' ').reduce(function(str, word, i, array) {
        str += word;
        if(lines.length === 0 || str.length > lines[lines.length-1].length || i === array.length - 1) {
            lines.push(str);
            return '';
        }
        return str;
    }, '');
    document.getElementById('trapezoid').innerHTML = lines.join('<br>');
</script>
like image 152
Paul Draper Avatar answered Jan 09 '23 15:01

Paul Draper


I know this is not a standard solution, and for the current year at least this would not be applicable to most users, but to do that you can use some CSS cutting edge features like "CSS Shape Modules".

If you are using Chrome a way to enable CSS regions (Chrome 20+) is going to chrome://flags and enable Experimental Web Platform features. A very simple test page could look like this:

<!DOCTYPE HTML>
<html>
  <head>
    <title>CSS Exclusions - Shape inside</title>
    <meta charset="UTF-8">

    <style type="text/css">
        #trapezoid {
            float: center;
            margin-top: 1em;
            width: 60em;
            height: 30em;
            -webkit-hyphens: auto;
            -webkit-shape-inside: polygon(0 0, 15% 0, 10% 20%, 0 20%);
            overflow: hidden;
        }
    </style>
  </head>

  <body>
    <div id="trapezoid">
      12345 1234 1234 1234 123 12345 1234 1234 123 1234 12345  
    </div>
  </body>

</html>

And this is what comes out:

     HTML-CSS output

You can look at some more examples here: http://adobe.github.io/web-platform/samples/css-exclusions/basic/shape-inside-simple.html

like image 38
merosss Avatar answered Jan 09 '23 14:01

merosss