Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda