如何防止填充丢弃我的DIV宽度?

时间:2016-10-13 19:35:27

标签: html css width padding

我有两个DIV,我想垂直堆叠......

<div id="searchContainer”>…</div>
<div id="searchResultsContainer”>…</div>

我分配了以下样式......

#searchContainer {
  padding: 10px;
  font-family: "Calibre", "Helvetica Neue", "Helvetica", "Roboto", "Arial", sans-serif;
  background-color: tan;
  width: 100%;
}

#searchResultsContainer {
  background-color:cyan;
  font-family: "Calibre", "Helvetica Neue", "Helvetica", "Roboto", "Arial", sans-serif;
  padding: 5px 0px 5px 0px;
  width: 100%;
}

然而,似乎在我的顶级DIV中添加填充会导致它比它下面的DIV更宽。我希望两个DIV都具有相同的宽度,但我希望顶部DIV具有填充,以便元素不会蜿蜒到边界。我怎么做?这是解释我的问题的小提琴 - https://jsfiddle.net/1zb5mqmo/

2 个答案:

答案 0 :(得分:1)

在填充的div上使用box-sizing: border-box;

#searchContainer {
    padding: 10px;
    font-family: "Calibre", "Helvetica Neue", "Helvetica", "Roboto", "Arial", sans-serif;
    background-color: tan;
    /* max-width: 1000px; */
    width: 100%;
    box-sizing: border-box;
}

box-sizing: border-box width和height属性包括内容填充和边框

box-sizing: content-box宽度和高度属性仅包含内容

更新了JSFiddle

答案 1 :(得分:0)

在这种情况下,只需删除宽度,您就可以将填充和边框结合起来而不会将其抛弃

&#13;
&#13;
#searchContainer {
  padding: 10px;
  font-family: "Calibre", "Helvetica Neue", "Helvetica", "Roboto", "Arial", sans-serif;
  background-color: tan;
}

#searchResultsContainer {
  background-color:cyan;
  font-family: "Calibre", "Helvetica Neue", "Helvetica", "Roboto", "Arial", sans-serif;
  padding: 5px 0px 5px 0px;
  border: 5px solid steelblue
}
&#13;
<div id="searchContainer">...</div>
<div id="searchResultsContainer">...</div>
&#13;
&#13;
&#13;