微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

html – 了解CSS表格单元格和百分比宽度

我正在检查Github如何显示以下菜单

如果您注意到,每个菜单项的宽度相等.在CSS中,我们应该给它任何百分比值,这背后的原因是什么?注意父div没有给出display:table属性.

div {
  border: 1px solid #000;
  border-radius: 4px;
}

div ul {
  padding: 0;
  margin: 0;
}

div ul li {
  display: table-cell;
  width: 1%;
  text-align: center;
  border-right: 1px solid #000;
  padding: 10px 0;
}

div ul li:last-child {
  border-right: 0;
}
<div>
  <ul>
    <li><a href="#">Commits</a>
    </li>
    <li><a href="#">Branch</a>
    </li>
    <li><a href="#">Contribution</a>
    </li>
    <li><a href="#">anything</a>
    </li>
  </ul>
</div>

宽度百分比背后的原因是什么?

解决方法

这与 automatic table layout的工作方式有关.尤其是:

A percentage value for a column width is relative to the table width. If the table has ‘width: auto’,a percentage represents a constraint on the column’s width,which a UA should try to satisfy. (ObvIoUsly,this is not always possible: if the column’s width is ‘110%’,the constraint cannot be satisfied.)

在您的情况下,您在每个table-cell元素上设置了一个小的百分比宽度.但是浏览器需要确保表格单元格填满表格的宽度(它本身与其包含的块一样宽),因此它必须扩展单元格以尽可能多地占用表格中的空间.

这导致近似等宽单元的原因是因为所有这些单元的百分比值相等.例如,如果您为其中一个单元格设置稍大的宽度,您将看到它变得更宽,而其他单元格变得更窄以适应:

div {
  border: 1px solid #000;
  border-radius: 4px;
}

div ul {
  padding: 0;
  margin: 0;
}

div ul li {
  display: table-cell;
  width: 1%;
  text-align: center;
  border-right: 1px solid #000;
  padding: 10px 0;
}

div ul li:first-child {
  width: 3%;
}

div ul li:last-child {
  border-right: 0;
}
<div>
  <ul>
    <li><a href="#">Commits</a>
    </li>
    <li><a href="#">Branch</a>
    </li>
    <li><a href="#">Contribution</a>
    </li>
    <li><a href="#">anything</a>
    </li>
  </ul>
</div>

但是,请注意,由于某些单元格的内容比其他单元格长,因此存在细微差别,并且在计算单元格宽度时会考虑此内容的长度.

使用小到1%的值的原因是您可以继续添加单元格,浏览器仍然会尝试尽可能均匀地分配可用宽度.你基本上告诉单元格它们不需要至少一定的宽度,所以你可以添加(虽然从技术上讲,1%仍然是东西).

没有分配元素的事实显示:table是无关紧要的,因为将在表格单元格周围生成匿名表格包装器,以便它们可以正确呈现.这个匿名表包装器的功能与带有display:table的非样式元素完全相同,这意味着表宽度是auto,用于计算百分比单元格宽度.

原文地址:https://www.jb51.cc/html/232415.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐