【问题标题】:border-box adding 1px space on top and bottom of a <a> block边框框在 <a> 块的顶部和底部添加 1px 空间
【发布时间】:2017-01-03 08:38:47
【问题描述】:

我需要一些帮助来确定 td 内 &lt;a&gt; 顶部和底部的 1px 空间来自何处,以及如何删除它。

&lt;a&gt; 显示为 flexbox,这是必需的,并填充整个 td。
这似乎是由border-sizing: border-box 引起的,但我不明白为什么(如果你删除它工作正常的属性,但我有点需要它,如果存在干净的替代方案,我宁愿找到另一个解决方案)。

table {
	border-collapse: collapse;
}

td {
	padding: 0;
}

td {
	width: 5rem;
	height: 5rem;
	padding: 0;
	border: 1px solid red;
}

a {
	display: flex;
	align-items: center;
	justify-content: center;
	flex-direction: column;
	width: 100%;
	height: 100%;
	border: 1px solid blue;
	outline: 0;
}

* {
  -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box;
}
<table>
  <tr>
    <td>
      <a href="#">
      </a>
    </td>
    <td>
      <a href="#">
      </a>
    </td>
    <td>
      <a href="#">
      </a>
    </td>
  </tr>
  <tr>
    <td>
      <a href="#">
      </a>
    </td>
    <td>
      <a href="#">
      </a>
    </td>
    <td>
      <a href="#">
      </a>
    </td>
  </tr>
</table>

【问题讨论】:

  • 只要在 Chrome、btw、Firefox 和(甚至!IE 11)中显示就可以了。
  • 在不同的浏览器中尝试。似乎不同的浏览器在边界框内部或外部计算边界。
  • @sinisake,你有解决办法让所有浏览器的行为方式都一样吗?

标签: css


【解决方案1】:

box-sizing: border-box 应用于* 选择器,并将box-sizing: content-box 应用于td &gt; a 元素。此外,width: 100% 可以从a 元素中删除。

* {
  -webkit-box-sizing: border-box; 
  -moz-box-sizing: border-box; 
  box-sizing: border-box;
}

table {
  border-collapse: collapse;
}

td {
  width: 5rem;
  height: 5rem;
  padding: 0;
  border: 1px solid red;
}

td > a {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  height: 100%;
  border: 1px solid blue;
  outline: 0;
  -webkit-box-sizing: content-box; 
  -moz-box-sizing: content-box; 
  box-sizing: content-box;
}
<table>
  <tr>
    <td>
      <a href="#">
      </a>
    </td>
    <td>
      <a href="#">
      </a>
    </td>
    <td>
      <a href="#">
      </a>
    </td>
  </tr>
  <tr>
    <td>
      <a href="#">
      </a>
    </td>
    <td>
      <a href="#">
      </a>
    </td>
    <td>
      <a href="#">
      </a>
    </td>
  </tr>
</table>

【讨论】:

  • 感谢您的回答。然而,它似乎只是因为属性 * { box-sizing: border-box } 已从我需要的 css 中删除:/ 我将对此进行调查!
  • 好的,然后将box-sizing: border-box 应用到* 并将box-sizing: content-box 应用到td &gt; a。上面已经更新了解决方案。