你未必知道的CSS小知识:你知道table里的empty-cells属性吗?

css里的empty-cells属性是所有浏览器都支持的,甚至包括IE8,它的用法是下面这个样子:

table {
  empty-cells: hide;
}

估计你从语义上已经猜出它的作用了。它是为HTML table服务的。它会告诉浏览器,当一个table单元格里没有东西时,就隐藏它。下面的演示里,你可以点击里面按钮,它会切换empty-cells的属性值,看看table的显示有什么变化。

HTML代码

<table cellspacing="0" id="table">
  <tr>
    <th>Fruits</th>
    <th>Vegetables</th>
    <th>Rocks</th>
  </tr>
  <tr>
    <td></td>
    <td>Celery</td>
    <td>Granite</td>
  </tr>
  <tr>
    <td>Orange</td>
    <td></td>
    <td>Flint</td>
  </tr>
</table>
  
<button id="b" data-ec="hide">切换EMPTY-CELLS</button>

CSS代码

body {
  text-align: center;
  padding-top: 20px;
  font-family: Arial, sans-serif;
}

table {
  border: solid 1px black;
  border-collapse: separate;
  border-spacing: 5px;
  width: 500px;
  margin: 0 auto;
  empty-cells: hide;
  background: lightblue;
}

th, td {
  text-align: center;
  border: solid 1px black;
  padding: 10px;
}

button {
  margin-top: 20px;
}

js代码

var b = document.getElementById('b'),
    t = document.getElementById('table');

b.onclick = function () {
  if (this.getAttribute('data-ec') === 'hide') {
    t.style.emptyCells = 'show';
    this.setAttribute('data-ec', 'show');
  } else {
    t.style.emptyCells = 'hide';
    this.setAttribute('data-ec', 'hide');
  }
};

演示

在上面的演示中,我为能让单元格的边框显示出来,在单元格的边框间添加了空隙。有时候这个属性不会有任何视觉效果,因为你必须让你里面有可见的东西。

阅读余下内容
 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注


京ICP备12002735号