表格不在div中心

时间:2018-08-01 07:22:57

标签: javascript html-table

我试图通过Javascript在div中创建3个表,然后将它们放入现有div的HTML中。请在此处找到完整的代码:

https://jsfiddle.net/s78n3dfe/

HTML文件

<div id = "tldr">
</div>

JavaScript文件

map1 = [["label1", 30], ["label2", 70]];
total1 = 100;
title1 = "dasdas";
var table1 = createTable(map1, total1, title1);
var table2 = createTable(map1, total1, title1);
var table3 = createTable(map1, total1, title1);

var divNode = document.createElement('div');
divNode.setAttribute("id", "labelInfo");
divNode.appendChild(table1);
  divNode.appendChild(table3);
  divNode.appendChild(table2);

  var tldr = document.getElementById('tldr');
  tldr.appendChild(divNode);

function createTable(map, total, title) {
  var table = document.createElement('table');
    table.setAttribute("class", "table");
    table.classList.add("table-striped");
    // table.setAttribute("class", "table-striped");
    table.setAttribute("style", "display: inline-block; width:33%;");

    var caption = table.createCaption();
    caption.setAttribute("style", "text-align: center;")
    caption.innerHTML = title.toString().bold();

    var header = table.createTHead();
    var firstRow = header.insertRow(0);
    var header1 = firstRow.insertCell(0);
    var header2 = firstRow.insertCell(1);

    header1.innerHTML = "Label".bold();
    header2.innerHTML = "Allocation".bold();

    var tblBody1 = document.createElement("tbody");
    tblBody1.setAttribute('class', 'percentageBody');
    tblBody1.setAttribute('style', 'display:block; border-top: 0px;');
    table.appendChild(tblBody1);

    for(label in map) {
      var row = document.createElement("tr");
      var labelCell = row.insertCell(0);
      var percentCell = row.insertCell(1);

      labelCell.innerHTML = map[label][0].bold();
      percentCell.innerHTML = map[label][1].toString().concat(" %");

      tblBody1.appendChild(row);
    }

    var tblBody2 = document.createElement("tbody");
    tblBody2.setAttribute('class', 'valueBody');
    tblBody2.setAttribute('style', 'display:none; border-top: 0px;');
    table.appendChild(tblBody2);

    for(label in map) {
      var row = document.createElement("tr");
      var labelCell = row.insertCell(0);
      var percentCell = row.insertCell(1);

      labelCell.innerHTML = (map[label][0]).bold();
      percentCell.innerHTML = (map[label][1]/100 * total).toFixed(0).toString();

      tblBody2.appendChild(row);
    }

    return table;
}

我面临的问题是表格朝向div的左侧而不是位于中央。我怎样才能使它们进入中心?

1 个答案:

答案 0 :(得分:2)

请检查以下代码:

从表格的CSS中删除内联块:

enter image description here