36

I have an element with a 70% width, and it is floating beside another element with 30% width. However, when I add 25px of padding, the element expands and breaks the format.

Is there any way to make padding increase the contents' distance from the element's edge, as opposed to making the element bigger?

.seventy {
  float: left;
  width: 70%;
  background-color: lightsalmon;
}

.thirty {
  float: left;
  width: 30%;
  background-color: lightgreen;
}

.padded {
  padding: 25px; /* Forces box onto next line */
}
<div>Works:</div>
<div class="seventy">70% wide</div>
<div class="thirty">30% wide</div>

<br><br>

<div>Broken:</div>
<div class="seventy">70% wide</div>
<div class="thirty padded">30% wide, padded</div>
mfluehr
  • 2,832
  • 2
  • 23
  • 31
nkcmr
  • 10,690
  • 25
  • 63
  • 84

2 Answers2

68

When you use the border-box model, the padding is included in the box size. See here for details.

.seventy {
  float: left;
  width: 70%;
  background-color: lightsalmon;
}

.thirty {
  box-sizing: border-box;
  padding: 25px;
  float: left;
  width: 30%;
  background-color: lightgreen;
}
<div class="seventy">70% wide</div>
<div class="thirty">30% wide</div>
mfluehr
  • 2,832
  • 2
  • 23
  • 31
codelark
  • 12,254
  • 1
  • 45
  • 49
  • 2
    Although corrext the support for box-sizing is a bit sketchy. Consider taking a small percentage off one of the widths and adding it to the padding. So your 2 widths+padding = 100%. EDIT~ Zeta Twos solution will guarentee a gap of 25px which would be a better solution. – sweetroll Mar 03 '11 at 05:22
11

I would create another element of the same type (may I guess it's a div?) inside the element and set that one to have a padding/margin of 25px.

For example:

<div id="wrapper">
 <div id="width30">
 </div>
 <div id="width70">
  <div id="padding25">
   Acctual content here.
  </div>
  </div>
 </div>
</div>
Zeta Two
  • 1,776
  • 1
  • 18
  • 37
  • 1
    This is a super smart solution people should take account of more. There's no sketchy css hacks, no potentially unsupported browsers, and it follows a clean container-content pattern. Glad to see some KISS CSS (CISS?), since it's so easy to over-engineer. – Nol Feb 13 '17 at 22:04