【问题标题】:Inserting an image into a table cell in HTML将图像插入 HTML 中的表格单元格
【发布时间】:2016-10-02 01:05:38
【问题描述】:

我发现在表格单元格中插入图像很困难。当我尝试用图像完全填充表格单元格时,表格单元格的大小正在增加并占据整个页面。 这是我的代码:

<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;
}

【问题讨论】:

  • 一定有其他的 CSS 或元素会影响您的解决方案,因为它应该可以工作 jsfiddle.net/742gk9fc
  • 我没有得到预期的输出 那么告诉我们你得到了什么输出以及为什么它不同。您是否使用萤火虫或代码检查器来检查元素的计算值?
  • 当我插入更高分辨率的图像时,表格单元格的大小会增加并占据整个网页。

标签: css html html-table css-tables


【解决方案1】:

这是因为&lt;table&gt; 在单元格中有一个默认间距,如果不需要,我们需要清除它。

<table class = "BarTable" style="width:100%;height: 100%" cellpadding="0" cellspacing="0">

【讨论】:

    【解决方案2】:

    您可以为包含图像的单元格赋予以下属性:

    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>

    【讨论】:

      【解决方案3】:

      图像和单元格边框之间有一点间隙¿这是问题吗?只有你设置了tdpadding: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>

      【讨论】:

        猜你喜欢
        • 2013-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-05
        • 1970-01-01
        • 1970-01-01
        • 2022-10-20
        • 1970-01-01
        相关资源
        最近更新 更多