【问题标题】:How to force the height of image inside left <td> follow the height of right <td> automatically?如何强制左侧 <td> 内的图像高度自动跟随右侧 <td> 的高度?
【发布时间】:2018-12-03 20:37:53
【问题描述】:

例如,在表格中,我在 td 中有一个图像,在右侧 td 有一些文本:

<table>
  <tr>
  <td><img src="https://www.gravatar.com/avatar/65756ce7bab4d76ac10456972dd9f21d?s=96&d=identicon&r=PG&f=1"/></td>
  <td>test1<br/>test2<br/>test3</td>
  </tr>
</table>

现在我希望图像的高度自动跟随其右侧 td 的高度:

当右td比图片短时,图片缩小:

当右侧td较高时,图像放大:

有没有办法做到这一点?我试过了:

<table style="position:relative;height:auto;">
  <tr style="position:relative;height:auto;">
  <td style="position:relative;height:auto;"><img src="https://www.gravatar.com/avatar/65756ce7bab4d76ac10456972dd9f21d?s=96&d=identicon&r=PG&f=1" style="position:relative;height:auto;"/></td>
  <td style="position:relative;">test1<br/>test2<br/>test3</td>
  </tr>
</table>

but I can't get my desired result.

【问题讨论】:

  • 您是否需要使用表格 - 它们不应该用于布局目的 - 仅用于表格数据(这似乎不是)

标签: html css html-table responsive-design


【解决方案1】:

您可以尝试将max-height CSS 规则设置为 100%

像这样:

<img src="https://www.gravatar.com/avatar/65756ce7bab4d76ac10456972dd9f21d?s=96&d=identicon&r=PG&f=1" style="max-height:100%;"/>

【讨论】:

    【解决方案2】:

    我相信使用 jQuery 比纯 CSS 更容易。 如果有帮助,您可以尝试以下解决方案:

    <!DOCTYPE html>
    <html>
    <head>
    <script
        src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    
    </head>
    <body>
        <table>
            <tr>
                <td id="first"><img
                    src="https://www.gravatar.com/avatar/65756ce7bab4d76ac10456972dd9f21d?s=96&d=identicon&r=PG&f=1" /></td>
    
                <td id="second">test1<br />test2<br />test3<br /> test1<br />test2<br />test3<br />
                    test1<br />test2<br />test3
                </td>
            </tr>
        </table>
    
        <script type="text/javascript">
            var h1 = $("#second").css("height");
            console.log(h1);
            $("img").css("height", h1);
        </script>
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-13
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多