Center label on a dynamic div

Asked

Viewed 57 times

-1

  • Look if here can help you. http://answall.com/questions/5225/centralizar-imagem-dentro-de-umadiv

2 answers

1


You can remove the position: absolute and add a display: block:

//************create div************
var div = document.createElement("div");
div.id="div";
div.style.width = "300px";
div.style.height ="300px";
div.style.border = "1px solid #000";
div.style.padding = "20px 10px";
div.style.background = "red";
div.style.cssFloat="left";
//div.style.position = "relative";
document.body.appendChild(div);

var id_div = document.getElementById("div");

//************create label************
var label = document.createElement("label");
label.innerHTML = "Graph";
label.style.font = "bold 20px arial,serif";
label.style.textAlign = "center";
label.style.display = "block";
id_div.appendChild(label);

1

You can do this with Flexbox.

var div = document.createElement("div");
div.id = "div";
div.style.width = "300px";
div.style.height = "300px";
div.style.border = "1px solid #000";
div.style.background = "red";
div.style.cssFloat = "left";
document.body.appendChild(div);

var id_div = document.getElementById("div");
var label = document.createElement("label");
label.innerHTML = "Graph";
label.style.font = "bold 20px arial,serif";
id_div.appendChild(label);
div {
  display: -webkit-flex;
   display: -ms-flexbox;
          display: flex;

  -webkit-align-items: center;
    -webkit-box-align: center;
       -ms-flex-align: center;
          align-items: center;

  justify-content: center;
}

All these positioning properties you are using in this case are unnecessary, as the property itself flex takes care of aligning the elements:

for (var i = 1; i <= 6; i++) {
  var el = document.createElement('div');
  var size = 50 * i;

  el.style.width = (size + 'px');
  el.style.height = (size + 'px');
  el.style.background = 'red';
  el.style.margin = '5px';
  document.body.appendChild(el);

  el.innerHTML = 'SOpt';
}
div {
  display: -webkit-flex;
   display: -ms-flexbox;
          display: flex;
  
  -webkit-align-items: center;
    -webkit-box-align: center;
       -ms-flex-align: center;
          align-items: center;
  justify-content: center;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.