CSS Right Margin Does Not Work Inside a Div With Overflow Scroll

Viewed 27434

I am trying to make two divs, one inside the other. The inner div is larger than the outer div, the outer div has overflow:scroll, and the inner div has margin:25px. So I do this:

#outer {
    width: 200px;
    height: 100px;
    overflow: scroll;
}
#inner {
    width: 400px;
    height: 200px;
    margin: 25px;
}

...

<div id="outer">
    <div id="inner">

    </div>
</div>

Instead of the inner div having a margin of 25px all the way around as expected, there is a 25px margin on THREE sides, but on the right side there is none. This is extremely counter-intuitive in my opinion.

If I add a middle div with a width large enough width to contain the inner div + 50px, we can make it look right, but that seems like a hacky workaround.

See my example on JSFiddle: http://jsfiddle.net/d3Nhu/16/

This happens the same way in every major browser. Is there any good reason for this behavior? Is this correct behavior according to the CSS specification?

NOTE: As you'd expect in this example, it makes no difference if you use overflow:auto instead of overflow:scroll.

EDIT: Please note that I'm not looking for a workaround for this behavior. (I already found one.) I'm looking for any insight as to the reason for this behavior, especially if it is documented in the CSS specification anywhere.

3 Answers

So the answers here don't actually solve the problem! (Although super detailed to the reason why it doesn't work)

I needed a solution. Here's mine for future readers. Use a combination of display:flex; with pseudo ::after element to fake the presence of a div to provide the margin needed.

.wrapper {
  display: flex;
  width: 400px;
  height: 100%;
  padding: 40px;
  background: lightGrey;
}

.lists_container {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  overflow: auto;
  position: relative;
  background: grey;
  padding: 40px;
  margin: 40px;
  width: 100%;
}

.card {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-width: 250px;
  max-width: 500px;
  height: 100px;
  margin: 50px 0;
  padding: 20px;
  background: orange;
  margin-right: 30px;
}

.card.last::after {
  content: '';
  position: absolute;
  right: -100px;
  width: 40px;
  height: 100%;
  background: red;
}
<div class="wrapper">

  <div class="lists_container">

    <div class="card">
    </div>

    <div class="card">
    </div>

    <div class="card last">
    </div>

  </div>

</div>

Related