为什么“ display:none”仍然占据空间?

时间:2019-03-20 03:11:04

标签: html css

我试图在移动设备上查看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>
如果有人能够帮助我,那就太好了。

1 个答案:

答案 0 :(得分:5)

您的标记无效。像<div>这样的block元素不能是<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类应用于表格单元格。