85

Given this simple structure:

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

with this CSS:

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

#child {
    width: 500px;      
}

Live demo: http://jsfiddle.net/523me/5/

Notice that the parent has a 20px padding and that the child overflows horizontally (because it is wider). If you scroll the parent all the way to the right, you'll see that the child touches the right edge of the parent.

So, the parent should have a right padding, but it is ignored. It seems that when the child has a fixed width, the right padding of the parent does not apply. (Is this specified by a standard? I would love to know. Please let me know if you find anything!)

Is there a way to force the right padding to be applied in this scenario without having to remove any of the elements from the flow (by floating or positioning)?

enter image description here

Screenshot 1 - The right padding is ignored. This is how all current browsers behave.

Screenshot 2 - The right padding applies. This is what I'm trying to accomplish. (Btw, the screenshot is from IE7, which is the only browser which does not ignore the right padding.)

4

5 回答 5

43

你正遭受这个问题的困扰。

我会通过给孩子一个边距(而不是给父母一个填充)来解决它:

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>

于 2012-04-07T14:30:37.460 回答
9

不知道,但补充说:

#child{
  display: inline-block;
}

似乎修复它:http: //jsfiddle.net/523me/6/

我只在最新的 Chrome 中测试过,可能不是跨浏览器

于 2012-04-07T14:15:10.070 回答
8

您可以将填充更改为边框。

padding: 20px;

border: 20px solid gray;
于 2012-04-07T14:17:32.413 回答
5

不,填充不会被忽略,但它仍然在父级内部。

请参阅更新的 jsFiddle,您可以在其中看到填充没有从其原始位置移动。

编辑:嗯,有一些异常。如果你给内部 div 一个右边距,那也会被忽略。嗯。支持你的问题。

于 2012-04-07T14:17:59.427 回答
0

将 padding-right 应用于溢出元素本身,并将背景移动到其直接子元素。

<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/

于 2012-04-07T14:29:25.507 回答