如何将高度100%应用于表格单元格内容

时间:2014-07-05 01:09:56

标签: html css

我在一行中有两个表格单元格。第一个有小div,第二个有大一个。第二个div延伸整行。如何将第一个div伸展到整个细胞?

这就是我得到的:

what I get

这就是我想要的:

what I want

HTML:

<table>
    <tr class="tr">
        <th class="th">
            <div class="div green">This div is short</div>
        </th>
        <th class="th">
            <div class="div blue">This div has more content so it pushes 
            the height of the whole row. However, the shorter div doesn't 
            stretch to the whole row. How do I fix this?</div>
        </th>
    </tr>
</table>

CSS:

.tr {
    width:100%;
    border:1px solid red;
    height:auto;
}
.th {
    display:table-cell;
    width:50%;
}
.div {
    /* What should be here? */
}
.green {
    background:green
}
.blue {
    background:blue
}

jsfiddle here

为什么我需要这个:表存储了大量的表格数据。表头包含用于过滤表内容的小部件,这些小部件具有可变高度。

1 个答案:

答案 0 :(得分:2)

最简单的方法是将height: 100%;添加到.inner并将height: auto;.tr更改为height: 100%;

.container{
    width:100%;
    border:1px solid red;
    height: 100%;
}
.outer{
    display:table-cell;
    width:50%;
}
.inner{
    height: 100%;
}
.green{
    background:green
}
.blue{
    background:blue
}

然而,这将意味着您的文本不再垂直居中在单元格中。即使这是您所展示的内容,也不是table-cell内容的默认/正确行为。这是因为里面有一个div嵌套。

您可以移除您的子div并简单地将其类滑动到<th>元素,它将使文本居中,在语义上更有效,并且使用更少的代码:

HTML:

<table>
    <tr class="container">
        <th class="outer green">first</th>
        <th class="inner outer blue">
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        </th>
    </tr>
</table>

<强> CSS:

.container {
    width: 100%;
    border: 1px solid red;
    height: 100%;
}

.outer {
    display: table-cell;
    width: 50%;
}

.green {
    background: green;
}

.blue {
    background: blue;
}

<强> JSFiddle Example

相关问题