将父div拉伸到表格内容的宽度

时间:2014-02-03 16:03:56

标签: html css

我正在尝试使用div拉伸来匹配子表的宽度。目前,当浏览器窗口缩小时,表格宽度超过其父div。

http://jsfiddle.net/Ydu2K/

<div id="parentdiv" style="width: 100%; background-color: green;">
    Some text in div.
    <table style="background-color: red;">
        <tr>
            <td>aaaa</td>
            <td>aaaa</td>
            <td>aaaa</td>
            <td>aaaa</td>
            <td>aaaa</td>
            <td>aaaa</td>
            <td>aaaa</td>
            <td>aaaa</td>
            <td>aaaa</td>   
            <td>aaaa</td>   
            <td>aaaa</td>   
            <td>aaaa</td>   
            <td>aaaa</td>   
            <td>aaaa</td>
            <td>aaaa</td>
            <td>aaaa</td>
            <td>aaaa</td>
            <td>aaaa</td>
            <td>aaaa</td>
            <td>aaaa</td>
            <td>aaaa</td>
            <td>aaaa</td>
        </tr>
    </table>
</div>

3 个答案:

答案 0 :(得分:2)

#parentdiv {
    display: inline-block;
    /* width: 100%;  remove */
}

http://jsfiddle.net/Ydu2K/6/embedded/result/

答案 1 :(得分:1)

以下是您可以使用的两个CSS选项:

选项1:

div {
    display: table;
}

Demo


选项2:

table {
    table-layout:fixed;
    width:100%;
}

Demo

答案 2 :(得分:0)

#parentdiv{
    position:relative;
}

以下是fiddle示例。顺便说一下,删除width:100%; inline-style