在td元素中垂直对齐的奇怪行为

时间:2014-08-13 19:01:41

标签: html css vertical-alignment

这个html渲染就像我希望它看起来那样(JSFiddle):

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<style media="screen" type="text/css">
    thead th, td {
        text-align: center;
    }
</style>
<body>
    <table class="table table-bordered table-hover">
        <tbody>
            <tr>
                <th>
                    X<br>Y
                </th>
                <td style="vertical-align: middle">
                    <span class="glyphicon glyphicon-remove"></span>
                </td>
            </tr>
        </tbody>
    </table>
</body>

但是我想将包括td元素样式在内的所有CSS移动到这样的地方(JSFiddle):

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<style media="screen" type="text/css">
    thead th, td {
        text-align: center;
    }
    td {
        vertical-align: middle;
    }
</style>
<body>
    <table class="table table-bordered table-hover">
        <tbody>
            <tr>
                <th>
                    X<br>Y
                </th>
                <td>
                    <span class="glyphicon glyphicon-remove"></span>
                </td>
            </tr>
        </tbody>
    </table>
</body>

由于我不明白的原因打破了glyphicon的垂直对齐。

有人可以解释原因吗?我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

默认引导样式在这里可以看到包含一个兄弟选择器,因此它的嵌入式样式具有更高的优先级。但内联样式更优先。

.table>tbody>tr>td {
padding: 8px;
line-height: 1.42857143;
vertical-align: top;
border-top: 1px solid #ddd;
}

enter image description here


您可以添加!important(我不建议这样做)

继续使用内联样式

.table>tbody>tr>td {
    vertical-align: middle;
}

<强> Demo

答案 1 :(得分:2)

我可以通过chrome开发人员工具看到bootstrap css覆盖了你的css。这是因为它使用了比您使用的更高优先级/更具体的css selector。 (同样id取代class

这就是为什么当你使用inline style时它可以工作,但是当你在外面指定它时它不起作用。

让它可以使用:

td {
        vertical-align: middle !important;
    }

或者如果您不想使用!important,您可以使用等效选择器作为bootstrap使用:

.table>tbody>tr>td{
 vertical-align: middle;
}
相关问题