2

这个问题与这个问题类似但有一个附加要求:我希望表格在其父级内具有 100% 的宽度。从那个问题复制的图像:

单元格间距图像

所以我希望“绿色部分”占据父级的 100% 宽度,并在单元格之间使用黄色间距。

我们可以使用表格上的负边距来“撤消”红色间距,至少在大多数情况下是这样。

但是,这并不总是适用于流体布局。实际上,只要有足够的内容使表格占据 100% 宽度(表格具有width:auto),它就可以正常工作。当没有足够的内容来做这件事时,问题就出现了,因为显而易见的解决方案width:100%并不能解决这个问题:表格将足够宽以容纳包含边框间距的父级,但我们正在剥离它,所以表格是不够宽了。

到目前为止,我发现的唯一“解决方案”是用长的(最好是不可见的)内容强制填充表格,以便它将填充到“真实”100%。但我希望有一个纯 CSS 解决方案……我也不想使用计算/表达式来获得尽可能大的浏览器支持。

body {padding: 1em}
section {background-color: yellow}
table {background-color: pink}
td {background-color: lightgreen}

table {border-spacing: 1em}

table.working, table.failing {margin: -1em;}
table.failing {width: 100%}
<body>
  <section>
    <h2>Simple table</h2>
    <table>
      <tr>
        <td>cell 1</td>
        <td>cell 2</td>
      </tr>
    </table>
    
    <br>
    
    <h2>Succesful "100% width" for both cells</h2>
    <table class="working">
      <tr>
        <td>cell with a lot of content to make sure that the table will be wide enough</td>
        <td>cell with a lot of content to make sure that the table will be wide enough</td>
      </tr>
    </table>
    
    <br>
    
    <h2>Unsuccesful 100% width</h2>
    <table class="failing">
      <tr>
        <td>table with</td>
        <td>100% width</td>
      </tr>
    </table>
    
    <br>
    
  </section>
  </body>

4

1 回答 1

0

为此,您需要手动处理一些 css。

body {padding: 1em}
section {background-color: yellow;}
table {background-color: pink;}
td {background-color: lightgreen}

table {border-spacing:0;}

table.working, 
/*table.failing {margin: -1em;}*/
table.failing {width: 100%; margin:0;}
table tr td{
  border:5px solid #ff0000;
  padding:10px;
}
.no-top{
  border-top:none;
}
.no-bottom{
  border-bottom:none;
}
.no-left{
  border-left:none;
}
.no-right{
  border-right:none;
}
<body>
  <section>
    <h2>Simple table</h2>
    <table cellpadding="0">
      <tr>
        <td>cell 1</td>
        <td>cell 2</td>
      </tr>
    </table>
    
    <br>
    
    <h2>Succesful "100% width" for both cells</h2>
    <table class="working">
      <tr>
        <td>cell with a lot of content to make sure that the table will be wide enough</td>
        <td>cell with a lot of content to make sure that the table will be wide enough</td>
      </tr>
    </table>
    
    <br>
    
    <h2>Unsuccesful 100% width</h2>
    <table class="failing">
      <tr>
        <td class="no-top no-left">table with</td>
        <td  class="no-top no-right">100% width</td>
      </tr>
      <tr>
        <td class="no-bottom no-left">table with</td>
        <td class="no-bottom no-right">100% width</td>
      </tr>
    </table>
    
    <br>
    
  </section>
  </body>

于 2016-08-11T15:19:08.077 回答