Dave Dave - 1 month ago 17
CSS Question

How do I prevent padding from throwing off my DIV widths?

I have two DIVs, which I would like to stack vertically …

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


I have the following styles assigned to them …

#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%;
}


However it seems that adding padding to my top DIV causes it to be wider than the DIV below it. I would like both DIVs to be the same width, but I would like the top DIV to have the padding so that the elements don’t scrunch up to the border. How do I do that? Here is the Fiddle that illustrates my problem — https://jsfiddle.net/1zb5mqmo/ .

Answer

Use box-sizing: border-box; on the padded div:

#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 The width and height properties include the content padding and border

box-sizing: content-box The width and height properties include only content

Updated JSFiddle