html - 让 td 元素的子元素占据整个宽度和高度

标签 html css html-table

我有一个 <td>带有一点填充的元素,当它的直接子元素是 <mark> 时,我想在整个表格单元格中添加阴影元素。

我正在使用 markdown 生成表格本身,所以只需添加一个类,如 <td class="highlight">不是真正的选择。

基本表格设置

这是一个基本的表格设置

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Type</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Ranger</td>
      <td>Dog</td>
    </tr>
    <tr>
      <td><mark>Frida <br/> Kahtlo</mark></td>
      <td><mark>Cat</mark></td>
    </tr>
  </tbody>
</table>

使用一些基本的 CSS

table {
    border-collapse: collapse;
}
table td, table th {
    border: 1px solid #ddd;
    padding: 8px;
    position: relative;
}

尝试 #1

一个想法是绝对定位 <mark>元素并将其固定到所有四个边:

td > mark {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    padding: 8px;
}

但是,这似乎不可能set the parent parent height from an absolutely positioned child , 所以内容溢出了 <td>

example one

table {
    border-collapse: collapse;
}
table td, table th {
    border: 1px solid #ddd;
    padding: 8px;
    position: relative;
}

td > mark {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    padding: 8px;
}
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Type</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Ranger</td>
      <td>Dog</td>
    </tr>
    <tr>
      <td><mark>Frida <br/> Kahtlo</mark></td>
      <td><mark>Cat</mark></td>
    </tr>
  </tbody>
</table>

尝试#2

另一个想法是像这样用负边距反转填充:

td > mark {
    display: block;
    margin: -8px;
    padding: 8px;
}

但是,如果在另一个单元格中有换行,我无法让子元素占据可用的全部高度

example two

table {
    border-collapse: collapse;
}
table td, table th {
    border: 1px solid #ddd;
    padding: 8px;
    position: relative;
}

td > mark {
    display: block;
    margin: -8px;
    padding: 8px;
}
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Type</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Ranger</td>
      <td>Dog</td>
    </tr>
    <tr>
      <td><mark>Frida <br/> Kahtlo</mark></td>
      <td><mark>Cat</mark></td>
    </tr>
  </tbody>
</table>

问:还有其他可能的方法吗?

最佳答案

使用大的box-shadow 并 overflow hidden

table {
    border-collapse: collapse;
}
table td, table th {
    border: 1px solid #ddd;
    padding: 8px;
}
td {
 overflow:hidden;
}
td > mark {
  display:inline-block;
  box-shadow: 0 0 0 50px yellow; 
}
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Type</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Ranger</td>
      <td>Dog</td>
    </tr>
    <tr>
      <td><mark>Frida <br/> Kahtlo</mark></td>
      <td><mark>Cat</mark></td>
    </tr>
  </tbody>
</table>

关于html - 让 td 元素的子元素占据整个宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58273940/

相关文章:

jquery - 卡在移动菜单的中心对齐中单击点

html - 表格单元格中的文本应仅在悬停时换行,否则应以省略号结尾

jquery - 图像 slider 自动循环功能

html - 如何减少图像和照片幻灯片之间的空间?

css - 有一个单独的 div 与其他的连续吗?

html - 在 dataTable 列中创建一个异步事件并根据响应呈现一个按钮

css - 我可以只在悬停时应用 CSS 过渡吗?

html - 红色的 Chrome 输入框

html - colspan 和 rowspan 什么时候可以在 HTML 表格中使用?

php - SQL 数据库信息未进入 HTML/PHP 表