0

I need to center a multiple line text in a div without using css, only with js. For example i have a div of 170px width, a SourceSansPro-Regular font and font size of 18px and this text for example :

i have
a
kitchen

The result i'm trying to achieve is to center each line in this 170px width div, like adding spaces before and after each words.

This is my code but without good result now :

    //input is my text
    function str_pad (input) { 
        
        
        parts = input.split('\n');
        parts = parts.trim();
        //container is my 170px width div
        var container = $(".pc-editable-canvas-positions-active .pc-active-editable-canvas .pc-rectangle");
        var size = get_char_size(container);
        var chars_per_line = get_num_chars(container, size);
        max = chars_per_line;
    
        parts = parts.map(s => s
            .trim()
            .padStart(s.length + Math.floor((max - s.length) / 2), '\xa0')
            .padEnd(max, '\xa0')
        );
        console.log(parts);
        newInput = parts.join('\n');
    
        return newInput;
    }
    
    function get_char_size(div) {
        
        var temp = $(' ').appendTo(div);
        //temp is a span with a "nbsp"
        var rect = $(".pc-rectangle").find('span')[0].getBoundingClientRect();
        var result = {
            width: rect.width,
            height: rect.height
        };
        temp.remove();
        return result;
    }
    
    function get_num_chars(div, char_size) {
        var width = div.width();
        return Math.floor(width / char_size.width);
    }

Each line is center with themselves but not center in my div.. if i change the character inside the span of my get_char_size function the text goes more left or more right but never centered in div..

How could achieve this ? What i forget to correctly have each text line length and adding the good number of space before and after them to simulate text-align center ?

Thanks for Helping

1 Answer 1

0

Try with this:

<div id="center-div">i have
a
kitchen</div>

const fontConstant = 1.91; // for font-family: Arial, sans-serif

const div = document.getElementById("center-div");

const style = window.getComputedStyle(div, null).getPropertyValue('font-size');
const fontSize = parseFloat(style);

const charactersPerRow = div.offsetWidth / (fontSize / fontConstant);

const innerHtml = div.innerHTML;

const words = innerHtml.split('\n');

const centeredWords = words.map(word => {
  const spacesToAdd = Math.round((charactersPerRow - word.length) / 2);
  let spaces = '';
  for (let i = 0; i < spacesToAdd; i++) {
    spaces += ' ';
  }
  return spaces + word + spaces;
});

let newInnerHtml = '';

centeredWords.forEach(word => {
    newInnerHtml += word + '\n'
});

div.innerHTML = '<pre>' + newInnerHtml + '</pre>';
4
  • Hi Vladimir, Your exemple add extra spaces to word are smaller than the longest but It doesn't solve my issue, hi need to add extra spaces before and after the longest word too to center it in the div and so adding the same amount of spaces to smaller words.. For exemple if my div can have 20 characters max based on font-size, if we take my text in this exemple, what i want to achieve is : (7 spaces)i have(7 spaces) (9,5 spaces)a(9,5 spaces) (6,5 spaces)kitchen(6,5 spaces)
    – devdev
    Commented Apr 5, 2021 at 17:18
  • Hello, I got it now. Updated the code appropriately. Please keep in mind you need to change the "fontConstant" depending on your font. Commented Apr 6, 2021 at 7:31
  • How can i found my fontConstant of my font ?
    – devdev
    Commented Apr 6, 2021 at 15:54
  • Sadly I am unable to find the constant for different fonts. It is average on all letters as some letters take less space and some take more (for example i and W). Commented Apr 12, 2021 at 13:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.