当子元素水平溢出时,为什么忽略父元素的右边填充?

考虑到这个简单的结构:

<div id="parent">
<div id="child">Lorem ipsum</div>
</div>

用这个 CSS:

#parent {
width: 200px;
height: 200px;
padding: 20px;
overflow-x: scroll;
}


#child {
width: 500px;
}

现场演示: http://jsfiddle.net/523me/5/

请注意,父级有一个 20px填充,并且子级水平溢出(因为它更宽)。如果向右滚动父元素,您将看到子元素触及父元素的右边缘。

因此,父函数应该有一个正确的填充,但是它被忽略了。当子元素具有固定宽度时,似乎不适用父元素的右填充。(是否有标准规定?我很想知道。如果你发现了什么,请告诉我!)

有没有一种方法可以强制在这个场景中应用正确的填充,即 没有必须从流中删除任何元素(通过浮动或定位) ?

enter image description here

屏幕截图1-右边的填充被忽略。这是所有当前浏览器的行为。

屏幕截图2-正确的填充应用。这就是我想要完成的。(顺便说一句,截图来自 IE7,它是唯一一个没有忽略正确填充的浏览器。)

25995 次浏览

Dunno but adding:

#child{
display: inline-block;
}

Seems to fix it: http://jsfiddle.net/523me/6/

I've only tested in latest Chrome, may not be cross-browser

You might change the padding to a border.

padding: 20px;

to

border: 20px solid gray;

No, the padding is not ignored, but it's still inside the parent.

See updated jsFiddle, where you can see that the padding hasn't moved from its original position.

Edit: Hm, there are some anomalies. If you give the inner div a right margin, that gets ignored too. Hm. Upvoting your question.

Apply padding-right to overflowing element itself, and move background to its direct child element.

<div id="parent">
<div id="child"><div>Lorem ipsum...</div></div>
</div>


<style>
#parent {padding-right: 0; }
#child {padding-right: 20px; }
#child > DIV {background: yellow; }
</style>

http://jsfiddle.net/523me/9/

You're suffering from this problem.

I would solve it by giving a margin to the child (and not a padding to the parent):

body {
padding: 2em;
}


#parent {
width: 200px;
height: 200px;
overflow-x: scroll;
background: gray;
}


#child {
width: 500px;
background: yellow;
margin: 20px;
display: inline-block;
}
<div id="parent">
<div id="child">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et turpis eu lorem consectetur blandit sed vel ligula. In lorem ligula, lacinia sed aliquet sed, congue quis tortor. In sed magna eros, eget blandit arcu. Nulla sit amet volutpat ipsum. Duis
quis nisl massa. Sed ipsum magna, tempus non malesuada in, gravida et sapien. Fusce a odio nulla, quis ultrices mauris. Maecenas in tellus id massa fringilla molestie.</div>
</div>