CSS计算的宽度与指定的宽度不同

时间:2017-11-17 09:54:18

标签: html css css3 flexbox

如此bin所示,为预览按钮指定的宽度为120像素,而渲染宽度始终为132像素(在不同的屏幕上)。



.btn-grey{
    cursor: pointer;
    background: #f1f3f6;
    border: 1px solid #d7d9e1;
    box-shadow: 1px 1px 1px #fff inset;
    border-radius: 3px;
    color: #838AAB;
    display: inline-block;
    height: 30px;
    padding: 0 5px;
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
            <div style="display: flex; width: 60%; justify-content: center;">
                <input name="preview" class="btn-grey" value="Preview" style="flex-basis: 120px; width: 120px; height: 35px;max-width: 120px; max-height: 35px; margin : 5px 5px 5px 5px " title="preview"/>
                <input name="load" class="btn-grey" type="submit" value="Load " style="width: 120px; height: 35px;max-width: 120px; max-height: 35px;margin : 5px 5px 5px 5px "/>
            </div>

</body>
</html>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:2)

只需在按钮样式中添加box-sizing: border-box;

即可

这将确保宽度和高度属性(以及最小/最大属性)包括内容,填充和边框,但不包括边距。

有关box-sizing的详细信息,请查看以下链接 https://www.w3schools.com/cssref/css3_pr_box-sizing.asp

答案 1 :(得分:2)

您只需将box-sizing: border-box添加到input

原因是元素box-sizing默认为content-box,这意味着默认情况下padding / border会添加到其width集,并且box-sizing: border-box它在其中计算。

Src:https://drafts.csswg.org/css-box-3/#width-and-height

作为备注,另一种选择是使用CSS Calc(),如下所示:

  • width: calc(wanted_width - left/right_padding - left/right_border)

Stack snippet

input {
  box-sizing:border-box
}

.btn-grey{
    cursor: pointer;
    background: #f1f3f6;
    border: 1px solid #d7d9e1;
    box-shadow: 1px 1px 1px #fff inset;
    border-radius: 3px;
    color: #838AAB;
    display: inline-block;
    height: 30px;
    padding: 0 5px;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
            <div style="display: flex; width: 60%; justify-content: center;">
                <input name="preview" class="btn-grey" value="Preview" style="flex-basis: 120px; width: 120px; height: 35px;max-width: 120px; max-height: 35px; margin : 5px 5px 5px 5px " title="preview"/>
                <input name="load" class="btn-grey" type="submit" value="Load " style="width: 120px; height: 35px;max-width: 120px; max-height: 35px;margin : 5px 5px 5px 5px "/>
            </div>

</body>
</html>

答案 2 :(得分:1)

嗨试试这个:

AlignedNew