Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/4278930/css-is-it-correct-that-text-content-of-a-div-overflows-into-the-padding

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...