Center label on a div dynamically

-1

I want to center a label that is created dynamically in the middle of the div, at the top. Here's the example: link

    
asked by anonymous 29.04.2015 / 13:38

2 answers

1

You can remove position: absolute and add 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);
    
29.04.2015 / 14:15
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 of these placement properties you are using in this case are unnecessary because the flex property itself is in charge 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;
}
    
29.04.2015 / 14:18