简体   繁体   English

用图像填充表格而不增加额外空间

[英]Fill a table with images without adding extra space

I need to build a 2x2 table where each cell contains only an image (20x20 size) without any additional space. 我需要构建一个2x2表,其中每个单元格仅包含一张图像(20x20大小),而没有任何其他空间。

I tried to force the size of the image and the table cells, but the resulting table still has extra spaces. 我试图强制图像和表格单元格的大小,但是生成的表格仍然有多余的空间。 What am I missing? 我想念什么?

http://jsfiddle.net/casaschi/M74nN/ http://jsfiddle.net/casaschi/M74nN/

HTML HTML

<table id="myTable" cellspacing="0" cellpadding="0" border="0">
    <tr>
       <td>
            <img src="http://pgn4web.casaschi.net/images/alpha/20/bp.png" />
       </td>
        <td>
            <img src="http://pgn4web.casaschi.net/images/alpha/20/bp.png" />
        </td>
    </tr>
    <tr>
        <td>
            <img src="http://pgn4web.casaschi.net/images/alpha/20/bp.png" />
        </td>
        <td>
           <img src="http://pgn4web.casaschi.net/images/alpha/20/bp.png" />
        </td>
    </tr>
</table>
<div id="out"></div>

CSS CSS

table {
    width: 40px;
    height: 40px;
    border: none;
    border-collapse: collapse;
    border-spacing: 0px;
    margin: 0;
    padding: 0;
}
td, img {
    border: none;
    margin: 0;
    padding: 0;
    width: 20px;
    height: 20px;
}

JS JS

document.getElementById("out").innerHTML = document.getElementById("myTable").offsetWidth + "x" + document.getElementById("myTable").offsetHeight;

Applying display: block to your <img> tags solved the problem. display: block应用于您的<img>标签解决了该问题。 Images are inline-block by default so I'm guessing that the extra whitespace around them caused the additional spacing. 图像默认情况下是inline-block ,因此我猜测图像周围的多余空格导致了额外的间距。

Add font-size:0 to td . font-size:0添加到td The spacing is caused by the whitespace around the images having a default of 16px font size. 间距是由图像周围的空白引起的,这些空白具有默认的16px字体大小。

Fiddle - http://jsfiddle.net/Xgwka/ 小提琴-http: //jsfiddle.net/Xgwka/

Easiest solution is to add font-size:0 to your td rule: 最简单的解决方案是将font-size:0添加到您的td规则中:

td, img {
    border: none;
    margin: 0;
    padding: 0;
    width: 20px;
    height: 20px;
    font-size:0;
}

jsFiddle example jsFiddle示例

You could also: 您还可以:

  • Float the images left with img {float:left;} img {float:left;}的图像

Use negative value of margin for td 对td使用负的保证金值

td, img {
border: none;
margin: -5px;
padding: 0;
width: 20px;
height: 20px;

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM