Home » Html » When a child element overflows horizontally, why is the right padding of the parent ignored?

When a child element overflows horizontally, why is the right padding of the parent ignored?

Posted by: admin November 29, 2017 Leave a comment

Questions:

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.)

Answers:

You’re suffering from this problem.

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

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

#child {
    width: 500px;
    background: yellow;  
    display: inline-block;
    margin: 20px; 
}

Demo: jsFiddle

Questions:
Answers:

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.

Questions:
Answers:

You might change the padding to a border.

padding: 20px;

to

border: 20px solid gray;

Questions:
Answers:

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

Questions:
Answers:

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/