html - 如何将表格单元格中的图像居中

标签 html css

目标是执行以下操作,其中蓝色矩形是固定大小的图像,“单词”位于这些图像的中心:

enter image description here

要用 table 做到这一点,我似乎需要将 tdspan 位置设置为绝对位置,然后是下一个单元格('text cell') 与第一个重叠,尝试将其位置设置为 relative 无效。设置 'left' 也没有效果 ...

这是我尝试过的解决方案:

<style>
    #column0 {
        position: absolute;
        text-align: center;
        vertical-align: middle;
        line-height: 50px;
    }
    #column0 span {
        position: absolute;
        left: 0;
        width: 100%;
    }
    #column1 {
        position: relative;
    }
</style>

<table>
    <tr><td id="column0"><img .../><span>word</span></td><td id="column1">text cell</td></tr>
</table>

你会怎么做? 我需要忘记 table 吗?


有效的解决方案(固定大小),感谢以下评论:

</style>
    #column0 {
        display:inline-block;
        width: 50px;
        height: 50px;
        background-image: url(...);
        text-align: center;
        vertical-align: middle;
        line-height: 50px;
    }
    #column1 {
        display:inline-block;
    }
</style>
<div>
    <div id="column0">word</div><div id="column1">text cell</div>
</div>

最佳答案

尝试:

#column0 {
    position: relative; /* should keep it in the layout */
}
#column0 span {
    position: absolute; /* should rip it out of the layout */
    top: 15px; /* just a wild guess here */
    left: 15px;
}

关键是设置父亲属和子绝对。 Absolute 应该将其从布局中剥离出来,并相对于最近的定位父级进行定位。

关于html - 如何将表格单元格中的图像居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22941432/

相关文章:

html - 将外部 HTML 文件包含到另一个 HTML 文件

css - Phonegap - 它是编译网页还是简单地包装它们

javascript - 按内容选择元素并删除其内容的第一个和最后一个字符

html - 四列等宽,0外边距,等内边距

html - 将 float div 添加到这个灵活的布局

html - 在css中使用哪个单位更好?

javascript - 切换 dojo 中 div 的显示在 Google Chrome 中无法正常工作

javascript - 没有 Index.html 设计的登录页面 - ngRoute (AngularJS)

jquery - 如何准确判断一个元素是否可滚动?

javascript - 覆盖 jQuery Mobile 背景 CSS