在HTML中将图像插入表格单元格

4

我在将图片插入表格单元格中遇到了困难。当我试图完全填充表格单元格时,表格单元格的大小会增加并占用整个页面。

这是我的代码:

<div id="bar">
    <table class = "BarTable" style="width:100%;height: 100%">
      <tr>
        <td style="width: 35%">
           <img src="131AZE.jpg" style="height:100%;width: 100%">
        </td>
        <td>Everyone</td>
       </tr>
    </table>
</div>

而 CSS 部分是:

#bar {
    height:45%;
    width: 100%;
}

table.BarTable,th,td {
    border:1px solid black;
    border-collapse: collapse;
    line-height: 0;
}

4
你的解决方案应该可以工作,但可能受到其他CSS或元素的影响。 https://jsfiddle.net/742gk9fc/ - thepio
我没有得到预期的输出。那么告诉我们你得到了什么输出以及为什么不同。你是否使用Firebug或代码检查器来检查元素的计算值? - Martin
当我插入更高分辨率的图像时,表格单元格的大小会增加,并且它会占用整个网页。 - Krishna Vamsi
你为什么在这里使用表格,你要展示哪些数据? - cloned
4个回答

0
这是因为 <table> 元素在单元格中有默认的间距,如果不需要的话我们需要清除它。
<table class = "BarTable" style="width:100%;height: 100%" cellpadding="0" cellspacing="0">

0

图片与单元格边框之间有一点间隙,这是问题吗?只有您设置了 td padding:0

#bar {
  height:45%;
  width: 100%;
}

table.BarTable,th,td {
  border:1px solid black;
  border-collapse: collapse;
  line-height: 0;
  padding:0;
}
<div id="bar">
  <table class = "BarTable" style="width:100%;height: 100%">
    <tr>
      <td style="width: 35%"><img src="http://lorempixel.com/400/200/" style="height: 100%;width: 100%"></td>
      <td>Everyone</td>
    </tr>
  </table>
</div>


0

您可以为带有图像的单元格设置以下属性:

width: 1%;
white-space: nowrap;

这将防止您的图像像您提供的代码一样被拉伸,而单元格将完美地包裹图像。

完整演示

#bar {
  height: 45%;
  width: 100%;
}

table.BarTable,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}

.myclass {
  width: 1%;
  white-space: nowrap;
}
<div id="bar">
  <table class="BarTable" style="width:100%;height: 100%">
    <tr>
      <td class="myclass"><img src="http://rs902.pbsrc.com/albums/ac222/jvac/pattern-background.png~c200"></td>
      <td>Everyone</td>
    </tr>
  </table>
</div>


0
问题是因为您将 CSS 样式 'height: 100%' 应用于单元格,并且图像的样式属性为 style="height:100%;width: 100%"。
这可能会解决问题。
<div id="bar">
  <table class="BarTable" style="width: 100%; height: 100%">
   <tr>
     <td style="width: 35%; height: 100%">
       <div style="height: 100%; display: flex; align-items: center; justify- content: center;">
        <img src="131AZE.jpg" style="max-height: 100%; max-width: 100%">
      </div>
    </td>
    <td>Everyone</td>
  </tr>
 </table>
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接