【问题标题】:Shrink an HTML table containing images proportionally according to screen size根据屏幕大小按比例缩小包含图像的 HTML 表格
【发布时间】:2013-01-12 04:35:34
【问题描述】:

考虑以下代码。如何以响应方式实现表格,以便在大屏幕上表格高度和宽度等于图像(例如 600x600)和在移动设备等较小屏幕上的表格按比例缩小图像的总和。例如,在屏幕宽度为 320 像素的 iPhone 上,我希望表格缩小到 320x320,同时保留图像纵横比。

<HTML>
<head></head>
<body>
    <div id="header"></div>
    <div id="table"
    <table style="height: 100%">
        <tr>
            <td>
                <img id="topleft" src="300x300.png">
            </td>
            <td>
                <img id="topright" src="300x300.png">
            </td>
        </tr>
        <tr>
            <td>
                <img id="bottomleft" src="300x300.png">
            </td>
            <td>
                <img id="bottomright" src="300x300.png">
            </td>
        </tr>
    </table>
</div>
<div id="footer"></div>
</body>
</html>

这是一张显示上述代码如何在移动 Safari 浏览器中呈现的图像。

【问题讨论】:

标签: html css responsive-design html-table


【解决方案1】:

自适应表维度可能很棘手。我建议的第一件事是将表格放在属性为position: relative 的div 中,然后以这种方式控制边距和大小。

<div id="myCont" style="">
    <table>
        <tr>
            <td> Hello! </td>
            <td> Aloha! </td>
        </tr>
        <tr>
            <td> Goodbye! </td>
            <td> Aloha! </td>
        </tr>
    </table>
</div>

然后是一些css:

#myCont {
    position: relative; 
    width: 100%;
}
#myCont table {
    width: 100%;
}
#myCont table tr td {
    width: 50%;
    position: relative;
}
.imgCls {
    width: 100%;
}

如果您随后将表格设置为 &lt;table cellspacing="0" cellpadding="0"&gt;,您将更容易获得准确的尺寸和“清晰的石板”。

此外,如果您只设置 width 属性,img 标签将始终尊重纵横比。

为此,我可能会推荐一个 jQuery 解决方案。

<img class="imgCls" src="/path/to/img.png" />

<script type="text/javascript">
$(document).ready(function(){
    var imgw = $('.imgCls').parent('td').css('width');
    $('.imgCls').css('width',imgw);
});
</script>

只要具有imgCls 类的图像的宽度(或希望)一致,这样的方法就应该起作用,var imgw 将采用它找到的第一个.imgCls 的宽度。

【讨论】:

    【解决方案2】:

    我建议你试试这个 css 代码:

    img{ width: 49%;  }
    

    http://jsfiddle.net/xeSLA/

    【讨论】:

      【解决方案3】:

      如果每行有 2 张图像,您可以将表格宽度设置为 100%,并将 td 和 img 宽度设置为大约 49%(以保留边框)。此外,如果您的图像可能小于可能的屏幕尺寸,请使用 img {max-width: 49%;}

      【讨论】:

      • 该解决方案在屏幕宽度大于高度的桌面上中断。它可能需要某种左右边距。嗯……
      • 它不应该中断...除非你使用 height: 100%。只定义宽度,高度会自动调整。
      • 啊,所以图像小于屏幕的一半。这意味着您使用了max-width。一种选择是通过使用width 来强制缩放它们(就像我在回答中写的那样),但这会使图像看起来很难看(插值)......另一种更好的解决方案是分解表格并允许超过此类屏幕每行 2 张图片(当然,如果您的应用计划这样做)。
      • 其实截图是使用“width”的结果。该应用程序需要一个 2x2 网格,所以很遗憾我不能简单地将图像添加到行中。我开始认为我需要用 javascript 解决这个问题。
      • 那么看来你在 td 元素上有position: relative...请尝试width: 99%
      猜你喜欢
      • 2014-06-21
      • 2017-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多