首页 > 解决方案 > 为什么“显示:无”仍然占用空间?

问题描述

我试图在移动设备上查看 HTML 页面时使表格中的特定单元格消失,并且在 PC 上具有 20% 的宽度,但是当我在移动设备上查看时,表格单元格是不可见的,但仍然占用空间。我在网上发现很多人说 display:none 并不意味着占用空间,但我似乎无法得到这个结果。

<style type="text/css">
  .mobileHide {display: inline; width : 20%;}
				
  @media only screen
  and (min-device-width : 320px)
  and (max-device-width : 480px){
    .mobileHide {
      display : none;
      width : 1% !important;
      overflow : hidden;
    }
  }
</style>
<table>
  <tbody>
    <tr>
      <div class="mobileHide">
        <td>
          This cell is meant to be 20% wide on PC but non-existent on mobile.
        </td>
      </div>
      <td>
        This cell is meant to be 60% wide on PC and 100% wide on mobile.
      </td>
      <div class="mobileHide">
        <td>
          This cell is meant to be 20% wide on PC but non-existent on mobile.
        </td>
      </div>
    </tr>
  </tbody>
</table>
如果有人能够帮助我解决这个问题,那就太好了。

标签: htmlcss

解决方案


您的标记无效。像这样的块元素<div>不能是<tr>;的子元素 在这种情况下,唯一有效的元素是<td><th>

在 Google Chrome 中,此标记被重新解释以将<div>元素放置在文档正文的根部,例如

<div class="mobileHide"></div>
<div class="mobileHide"></div>
<table>
  <tr>
    <td>
      This cell is meant to be 20% wide on PC but non-existent on mobile.
    </td>
    <td>
      This cell is meant to be 60% wide on PC and 100% wide on mobile.
    </td>
    <td>
      This cell is meant to be 20% wide on PC but non-existent on mobile.
    </td>
  </tr>
</table>

如果要在移动设备上隐藏表格单元格,请将mobileHide类直接应用于表格单元格。


推荐阅读