【问题标题】:Centered text in fully clickable table cell完全可点击的表格单元格中的居中文本
【发布时间】:2018-11-19 02:04:28
【问题描述】:

这个快把我逼疯了,可惜我的 CSS 还不是很好。

如何将水平和垂直居中的文本链接放入完全可点击的表格单元格中?

我研究过,尝试了几种解决方案,但都没有奏效。到目前为止,这是我最好的方法:

HTML

<table class="dataTable">
<thead>
    <tr>
        <th>Header 1</th>
        <th>Header 2</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>
            <a href="#">I wanne be centered!</a>
        </td>
        <td>
            <a href="#">Me too!</a>
        </td>
    </tr>
</tbody>
</table>

CSS

.dataTable td a {
    width: 100%;
    height: 100%;
    text-align: center;
    vertical-align: middle;
    display:block;
    text-decoration: none;
}

.dataTable td {
    display:inline-block;
}

这个给了我居中的文本,但链接只覆盖单元格的宽度,而不是高度。如果我将链接的 css 更改为 display:inline-block,则整个单元格是可点击的,但文本不再垂直居中。

我都需要。救命!

【问题讨论】:

  • 请注意,td 在您的示例中不是 .datatable 的子级。
  • @abiessu:td 绝对是.dataTable 的子代; table 中的所有内容都是孩子。
  • 您是否尝试在父tr 元素上设置固定高度(即像素高度)?只有这样子元素的高度才能设置为 100%。
  • @DavidThomas:我承认他们是后代,但不是孩子。但是,如果 CSS 不能区分差异,我承认这一点。
  • @abiessu:好的,我想我明白你的意思了,但值得注意的是空格匹配所有后代,所以选择器适合这里的用例。如果 OP 使用了子组合器,那么这将是一个问题,但是 CSS 并不真正关心元素之间祖先的“深度”。

标签: html css html-table


【解决方案1】:

我认为你应该删除它:

.dataTable td {
    display:inline-block;
}

see this fiddle

【讨论】:

  • 我删除了css,没有效果。我还尝试按照 Markus Hofmann 的建议在 .dataTable tr 上设置一个固定的像素高度,但没有效果。
【解决方案2】:

我认为这就是你想要的:

.dataTable {
    text-align: center;
}

.dataTable a {
  display: inline-block;
  width: 100%;
  height: 100%;
}

/* Just for better visualization */
.dataTable td {
  background: red;
}
<table class="dataTable">
<thead>
    <tr>
        <th>Header 1</th>
        <th>Header 2</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>
            <a href="#">I wanne be centered!</a>
        </td>
        <td>
            <a href="#">Me too!</a>
        </td>
    </tr>
</tbody>
</table>

如果你想增加td的高度,你应该通过修改a的高度来实现。否则,链接不会占据整个单元格的高度。您可以使用height 属性或line-height 来实现。

.dataTable {
    text-align: center;
}

.dataTable a {
  display: inline-block;
  width: 100%;
  height: 100%;
  line-height: 5; /* To get a 5 text lines high cell */
}


.dataTable td {
  /* Just for better visualization */ 
  background: red;
}
<table class="dataTable">
<thead>
    <tr>
        <th>Header 1</th>
        <th>Header 2</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>
            <a href="#">I wanne be centered!</a>
        </td>
        <td>
            <a href="#">Me too!</a>
        </td>
    </tr>
</tbody>
</table>

【讨论】:

    【解决方案3】:

    将您的文本包装在一个

    div style="padding-top:5px;".
    

    这将使它大致居中。

    【讨论】:

      猜你喜欢
      • 2011-11-30
      • 2018-09-23
      • 2014-05-05
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      相关资源
      最近更新 更多