代码之家  ›  专栏  ›  技术社区  ›  Urbycoz

如何使链接填充不同高度的表格单元格?

  •  2
  • Urbycoz  · 技术社区  · 7 年前

    我有一张有两个牢房的桌子。一个有链接,另一个有图像。

    <table>
      <tr>
        <td>
          <a href="https://google.com">My Link</a>
        </td>
        <td>
          <img src="https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" />
        </td>
      </tr>
    </table>

    如何使第一个单元格的整个作为链接而不仅仅是文本本身工作?

    可能有不同大小的图像,所以我不能依赖于它的固定高度。

    jsfiddle

    3 回复  |  直到 7 年前
        1
  •  4
  •   Sensoray    7 年前

    由于图像高度总是在变化,请从 <a> . 使链接完全位于块内,从而占用整个空间。这将使td的宽度仍然是单元格的内容,以便链接可以覆盖整个空间。

    td{
      border:1px solid;
      position:relative;
    }
    td a{
      position:absolute;
      top:0;
      bottom:0;
      right:0;
      left:0;
    }
    <table>
      <tr>
        <td>
          <a href="https://google.com"></a>
          My Link
        </td>
        <td>
          <img src="https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" />
        </td>
      </tr>
    </table>
        2
  •  2
  •   Clément Jacquelin    7 年前

    你可以这样做:

    a {
      display: block;
      height: 100%;
    }
    table{height: 100%;}
    td{height: 100%;}
    <table>
      <tr>
        <td>
          <a href="https://google.com">My Link</a>
        </td>
        <td>
          <img src="https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" />
        </td>
      </tr>
    </table>
        3
  •  1
  •   Temani Afif    7 年前

    您可以创建一个伪元素来覆盖td的区域:

    a:before {
      content: "";
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 0;
    }
    
    td {
      position: relative; /*Make it relative to td*/
      border: 1px solid;
    }
    <table>
      <tr>
        <td>
          <a href="https://google.com">My Link</a>
        </td>
        <td>
          <img src="https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" />
        </td>
      </tr>
    </table>