Reputation: 3
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
Upvotes: 0
Views: 240
Reputation: 319
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>';
Upvotes: 0