正确地将宽度拉伸到IE6和IE7中的内联块元素的100%

时间:2010-04-30 04:36:05

标签: internet-explorer internet-explorer-6 internet-explorer-7 css

我有以下标记,我试图让第二个表的右侧与其上方标题的右侧对齐。这适用于IE8,Firefox和Chrome,但在IE6 / 7中,表格被错误地拉​​伸以填充页面的宽度。

我正在使用Trip Switch hasLayout trigger在IE6 / 7中应用inline-block

是否有人知道如何(或者甚至)我只能填充表格以填充IE6 / 7中用inline-block显示的包装元素的自然宽度?

您可以在http://jsbin.com/uyuva处看到正常运行的代码。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Test</title>
<style>
.wrapper {
    display: inline-block;
    border: 1px solid green;
}
/* 
 display: inline-block triggers the wrapper element to have layout for IE 6/7.
 The trip switch then provides the inline component of the display behaviour.
 See http://www.brunildo.org/test/InlineBlockLayout.html for more details.
 */
.wrapper {
    *display: inline;
}

table {
    border: 1px solid red;
}
</style>
</head>
<body>
<h1>No width on table:</h1>
<div class="wrapper">
    <h2>The right hand side of the table doesn't stretch to the end of this heading</h2>
    <table><tr><td>foo</td></tr></table>
</div> text

<h1>Width on table:</h1>
<div class="wrapper">
    <h2>The right hand side of the table should stretch to the end of this heading</h2>
    <table style="width: 100%"><tr><td>foo</td></tr></table>
</div> text
</body>
</html>​

更新:这是问题的另一个例子,这次不使用表并使用绝对定位的容器元素。您可以在http://jsbin.com/igila4处看到正在运行的代码。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Test</title>
<style>
div {
    position: absolute;
    border: 1px solid red;
}

input {
    width: 100%;
    *width: 95%; /* fudge factor for IE 6/7 which don't support box-sizing */
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
}

textarea {
    width: 400px;
}
</style>
<body>
The width of the input and textarea below should be identical.<br/>
<div>
    <input value="This is an input with width 100%"><br/>
    <textarea>This is a text area with width 400px.</textarea>
</div>
</body>
</html>

3 个答案:

答案 0 :(得分:4)

这似乎不能通过CSS实现。

我故意避免使用脚本,因为我更喜欢利用浏览器在页面动态操作时为我回复所有内容,而不必编写手动代码来更新宽度。

最后,我通过指定表格的最小宽度来解决问题,这个宽度应该比我所拥有的任何标题的长度都宽。

Internet Explorer 6和7不支持min-width,但由于我有一个创建我正在显示的表的通用脚本,我动态创建一个额外的thead元素,该元素具有单个单元格跨越我设计的每一列有效地给我相同的结果:

<强> CSS

table {
    min-width: 600px;
}
th.min-width {
    *width: 600px;
}

HTML表格结构

<table>
    <thead><tr><th colspan="3" class="min-width"></th></tr></thead>
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>Column 3</th>
        </tr>
    </thead>
    <tbody>
        ...
    </tbody>
</table>

答案 1 :(得分:1)

如果你可以在包装器上设置一个宽度(例如50em),那么表格将扩展到包装器的宽度。

但是,如果您需要动态地填充包装器,那么您可以使用javascript将表的width设置为包装器的offsetWidth。这是添加了javascript的页面:http://jsbin.com/uyuva/5

我只在运行兼容模式的IE 8上测试过,因为我没有IE 6/7。

答案 2 :(得分:0)

您需要使用javascript来获取h2的宽度并将其应用于表格。我不相信CSS可以在每个浏览器中处理你需要的东西 coughIEcough

这是一个很好的sample来引用