html - 如何确保单元格不会因内容而调整大小?

标签 html css

当设置table-layout:fixed时,所有单元格都会变得相同大小,直到向其中添加一些内容为止。即使内容存在,有没有办法保持它们的大小相等?内容可以具有作为单元格百分比的宽度/高度,也可以具有固定宽度。该表格是响应式的(如果内容溢出,则应将其隐藏)。

现在的样子( jsfiddle ):

table {
  table-layout: fixed;
  width: 40vw;
  height: 40vw;
}
td {
  border: 3px solid grey;
  padding: 0px;
  width: 40px;
}
.aligner {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.content {
  height: 60px;
  width: 90%;
  background-color: green;
  border-radius: 20px;
}
<table>
  <tr>
    <td></td>
    <td>
      <div class="aligner">
      </div>
    </td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td>
      <div class="aligner">

      </div>
    </td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td>
      <div class="aligner">
        <div class="content">
          hello world
        </div>
      </div>
    </td>
    <td></td>
  </tr>
</table>

如果可以仅使用 Flexbox(即没有表格)来解决它就好了,但我不知道如何使其始终具有固定数量的相同大小的行和列,以便它看起来像中的表格图像。

小:

small

中:

medium

大:

large

最佳答案

仅使用CSS,您可以直接在td上设置宽度高度,并使用position:relative + overflow:hidden,然后将内部 div 设置为 position:absolute

<强> jsFiddle

td {
  border: 3px solid grey;
  width: 10vw;
  height: 10vw;
  text-align: center;
  position: relative;
  overflow: hidden;
}
.aligner {
  position: absolute;
  left: 0; right: 0; top: 0; bottom: 0;
  margin: auto;
  height: 60px;
  width: 90%;
  background-color: green;
  border-radius: 20px;
}
<table>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td><div class="aligner">hello world</div></td>
    <td></td>
  </tr>
</table>

或者使用伪元素+填充技巧来制作方形表格单元格。

<强> jsFiddle

table {
  width: 40vw;
}
td {
  border: 3px solid grey;
  text-align: center;
  position: relative;
  overflow: hidden;
}
td:before {
  content: "";
  display: block;
  padding-top: 100%;
}
.aligner {
  position: absolute;
  left: 0; right: 0; top: 0; bottom: 0;
  margin: auto;
  height: 60px;
  width: 90%;
  background-color: green;
  border-radius: 20px;
}
<table>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td><div class="aligner">hello world</div></td>
    <td></td>
  </tr>
</table>

关于html - 如何确保单元格不会因内容而调整大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35256258/

相关文章:

javascript - 使用 JavaScript 动态生成的选择选项下拉菜单

html - 如何修复单选按钮的::before伪元素的边界锯齿问题?

html - 网页中的页脚显示为内联元素而不是 block 元素

ios - 我可以做些什么来删除出现在这个 SoundCloud 小部件周围的 1px 边框吗?

javascript - 带悬停的 Jquery 工具提示

javascript - 标题标签中的 div 自动关闭

jquery - 菜单锚定到最外层的 div

html - 横向模式下的移动媒体查询?

html - 包装背景图像不会从页面上消失

javascript - 根据宽度计算div的高度并保持比例