Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
How do I create left and right margins for individual lines of text with vanilla JS?
const carriage = (e) => {
  let content = document.activeElement
  // alert('hi')
  // let space = content.textContent += '     '
  let space = ' '
  
  for (let i = 0; i < 33; i++) {
    content.textContent += space;  
  }
}

I know I'm way off, but how do I create left and right margins for individual lines of text using vanilla javascript? I'm trying to do this using a contenteditable div.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Without knowing the actual problem, here is a solution assuming you just want to add padding around the content.

The important parts of this solution is this in the CSS

padding:20px; Adds 20px padding to the top, right, bottom and left of the div box-sizing: border-box; Allows the border/padding to not affect the width or height of the div

.editor{
  height:400px;
  width:400px;
  border:1px solid #000;
  padding:20px;
  box-sizing: border-box;
}
<div contenteditable="true" class="editor"></div>

about 4 years ago · Juan Pablo Isaza Report

0

Adding the css white-space: pre will preserve the spaces in your inner text content for your div.

A loop over each line (split) in the inner text and a recombination (join) at the end will staple it back together with each line having the space padding on the left and right.

const carriage = (e) => {
  let content = document.querySelector('div');
  let space = ' '
  
  let linesOfContent = content.innerText.split('\n');
  content.innerText = linesOfContent.map((line) => {
    let newLine = line;
    for (let i = 0; i < 33; i++) {
     newLine =  space + newLine + space;  
    }
    return newLine
  }).join('\n'); 
}

carriage();
div {
  white-space: pre;
  border: 1px solid lightgray;
}
<div contenteditable="true">Hello
Hi
Goodbye</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!