CSS: Is it correct that text content of a div overflows into the padding?

Nigel Alderton picture Nigel Alderton · Nov 25, 2010 · Viewed 29.8k times · Source

I expected that the padding inside a div would remain clear of any text. But given the following html/css, the content-text spills out into the padding;

<div class="foo">helloworld</div>

.foo {
  float: left;
  overflow: hidden;
  background: red;
  padding-right: 10px;
  width: 50px;
  border: 1px solid green;
}

The text overflows it's 50px size and into the 10px padding. Is that by design? If so it seems pretty dumb - padding isn't padding if it's got stuff in it! Or am I just doing something wrong?

Regards, CSS newbie.

Answer

Brant Bobby picture Brant Bobby · Nov 25, 2010

This is the correct behavior. overflow: hidden will clip content that extends outside the box. Padding is inside the box, so content will happily overflow into that space if necessary.

CSS Box model
(source)

To get the effect you seem to be aiming for, one solution is wrap your div.foo in an another div and set the background on that one instead, like this:

<div class="foowrapper">
    <div class="foo">purrrrrrrrr</div>
</div>

.foo {
    overflow: hidden;
    width: 40px;
}
.foowrapper {
    padding-right: 10px
    background: red;
    border: 1px solid green;
}