How to flatten nested divs to display them in a CSS grid?

前端 未结 3 609
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 13:29

I generate a table (with vue.js) from an object which is supposed to be two columns wide. Each of the columns comes from the key and value of the object. This is equivalent

3条回答
  •  [愿得一人]
    2020-11-29 14:08

    If possible, I would advise to change your Vue.js code to not generate the unneeded nested div level, and make it this:

    #table {
      display: grid;
      grid-template-columns: auto 1fr;
    }
    #table > div { border: 1px dotted black; }
    this is something long on the first row
    short 1st row
    wazaa 2nd row
    wazii 2nd row

    If that's not possible then you could use Javascript to achieve the same, but client side. You could also use the display:contents from the answer by @Temani but it has rather limited browser support with possibly buggy results.


    If you prefer a Javascript solution instead, you can use this:

    (function() {
      var table = document.getElementById("table");
      var divs = [...table.childNodes]; // use ... to enumerate the items immediately
      for (var i = 0; i < divs.length; i++) {
        var div = divs[i];
        while (div.childNodes.length > 0)
          table.appendChild(div.childNodes[0]);
        div.remove();
      }
    })()
    #table {
      display: grid;
      grid-template-columns: auto 1fr;
    }
    #table > div { border: 1px dotted black }
    this is something long on the first row
    short 1st row
    wazaa 2nd row
    wazii 2nd row

提交回复
热议问题