CSS text justify with letter spacing

后端 未结 9 1290
时光取名叫无心
时光取名叫无心 2020-12-01 12:29

Is there a way to automatically justify words using letter spacing, each in its row, to a defined width, using CSS?

For example, \"Something like this\" would look,

9条回答
  •  醉话见心
    2020-12-01 12:42

    I just made a JQuery script from table's Tony B approach. Here is the JSFiddle https://jsfiddle.net/7tvuzkg3/7/

    This script creates a table with each char in a row. This works with full sentence. I'm not sure this is fully optimized.

    justifyLetterSpacing("sentence");
    
    function justifyLetterSpacing(divId) {
    
    	// target element
    	domWrapper = $('#' + divId).clone().html('');
    	// construct 
    	$('#' + divId).contents().each(function(index){
          // store div id to td child elements class
    	  var tdClass = divId ;
          // split text 
    	  $textArray = $(this).text().split('');
          // insert each letters in a 
    	  for (var i = 0; i < $textArray.length; i++) {
            // if it's a 'space', replace him by an 'html space'
            if( $textArray[i] == " " )  {
                $('')
                    .addClass(tdClass)
                    .html("  ")
                    .appendTo(domWrapper);
            }// if it's a char, add it
            else{  
                $('')
                    .addClass(tdClass)
                    .text($textArray[i])
                    .appendTo(domWrapper);
            }
    	  }
    	});
        // create table
        table = 
        $( "" ).append( 
            $( "" ).append( 
                $( "" ).append( 
                    ( domWrapper ).children('td') 
                ) 
            )
        );
        // replace original div
    	$('#' + divId).replaceWith( table );
    }	
    #sentence {
      width : 100%;
      background-color : #000;
      color : #fff;
      padding : 1rem;
    }
    
    
    LOREM IPSUM DOLOR

    提交回复
    热议问题