0

你可能认为它是重复的,但我不这么认为,因为我说的是表格而不是图像!

我尝试使用以下代码在 div 的中心水平和垂直设置一个表格。这些代码适用于图像,但是当我放置一个表格而不是图像时,它似乎看不到表格,然后将跨度大小设置为 100%,并且表格显示在 div 下方,而不是在 div 的中心。

代码:

<style>
.wraptocenter {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    width:155px;
    height: 160px;
    background-color:#999;
    display: block;
}
.wraptocenter * {
    vertical-align: middle;
}

.wraptocenter span {
    display: inline-block;
    height: 100%;
    width: 1px;
}

</style>
<!--[if lt IE 8]><style>
.wraptocenter span {
    display: inline-block;
    height: 100%;
}
</style><![endif]-->
<div class="wraptocenter">
    <span></span>
    <table border="1" width=" 70%">
        <tr height="10px">
            <td width="10px" height="10px"></td>
            <td width="10px" height="10px"></td>
        </tr>
        <tr height="10px">
            <td height="10px"></td>
            <td height="10px"></td>
        </tr>
    </table>
</div>

如果你放一张图片,一切都很好,但桌子不行!

4

1 回答 1

1

http://jsfiddle.net/FW2Af/

您的代码仅以 为中心元素display:inline-block,例如图像。但一张桌子有display:table

然后,您可以通过创建一个包含您的表的内容来解决divdisplay:inline-block

如果您希望表格的宽度为 wraptocenter 宽度的 70%:

  • 摆到width:100%桌子上
  • 设置width:70%为容器div

此外,您还有width="10px"顶部单元格。如果表格的宽度为 70%,那是无稽之谈。

编辑:

我已经修复了 IE 7(及之前),因为如果你设置display:inline-block一个元素是一个块,它仍然是一个块,所以你必须设置diplay:inline才能使它成为display:inline-block

<!--[if lt IE 8]><style>
.wraptocenter>div{
    display:inline;
}
</style><![endif]-->

<span>此外,在某些浏览器上会显示和之间的空格<div>,因此表格没有完全居中。

解决方案是:

.wraptocenter {
    font-size:0;
}
.wraptocenter>div{
    font-size:16px; /* Or whatever you want */
}

(字体:https ://stackoverflow.com/a/8902198/1529630 ,这是个好主意,因为在这种情况下使用浮动会破坏居中)

在这里看到它:http: //jsfiddle.net/FW2Af/2/

编辑3:

你说在 IE 8 上什么都没有显示。对我来说它有效,但不是黑色边框,而是白色。固定在这里:http: //jsfiddle.net/FW2Af/3/

.wraptocenter td{
    border:1px solid black;
}
于 2012-08-25T23:10:22.620 回答