Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

139
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda