Div with display:table预留1px以上

时间:2016-01-20 16:15:31

标签: html css

我有四个div

<div id="blockContainer">
    <div id="blockA">LogInR</div>
    <div id="blockB">Logo</div>
    <div id="blockC">Search</div>
    <div id="blockD">Post</div>
</div>

和风格是:

#blockA {
    border: 1px solid #f0f;
    display: table;
    width: 100%;
}
#blockB {
    border: 1px solid #f0f;
    display: table-cell;
}
#blockC {
    border: 1px solid #f0f;
    display: table-cell;
    width: 100%;
}
#blockD {
    border: 1px solid #f0f;
    display: table-cell;
}

所以我的blockA width:100%保留1px更多。

2 个答案:

答案 0 :(得分:1)

这是因为浏览器计算盒子大小的方式。它将边框的宽度添加到100%宽度。您需要使用*{box-sizing: border-box;}更改其计算方式:

*{box-sizing: border-box;}
#blockA {
    border: 1px solid #f0f;
    display: table;
    width: 100%;
}
#blockB {
    border: 1px solid #f0f;
    display: table-cell;
}
#blockC {
    border: 1px solid #f0f;
    display: table-cell;
    width: 100%;
}
#blockD {
    border: 1px solid #f0f;
    display: table-cell;
}
<div id="blockContainer">
    <div id="blockA">LogInR</div>
    <div id="blockB">Logo</div>
    <div id="blockC">Search</div>
    <div id="blockD">Post</div>
</div>

答案 1 :(得分:0)

默认情况下,使用宽度100%和边框将生成100%+边框宽度元素。尝试使用box-sizing。

#blockA, #blockB, #blockC, #blockD {
    box-sizing: border-box;
}

#blockA {
    border: 1px solid #f0f;
    display: table;
    width: 100%;
}
#blockB {
    border: 1px solid #f0f;
    display: table-cell;
}
#blockC {
    border: 1px solid #f0f;
    display: table-cell;
    width: 100%;
}
#blockD {
    border: 1px solid #f0f;
    display: table-cell;
}
<div id="blockContainer">
    <div id="blockA">LogInR</div>
    <div id="blockB">Logo</div>
    <div id="blockC">Search</div>
    <div id="blockD">Post</div>
</div>