Search code examples
cssoverflowpaddingmargin

How do you make overflow-y property account for an elements margin, without affecting overflow-x?


The <main> element on my page does not include the margin-bottom value of it's last element in the calculation of its content-box height. To fix this, I set the overflow-y: auto, now the margin of the last element is taken into account.

The problem is that this causes horizontal scrollbars on smaller screens. How do I only set overflow-y, without affecting overflow-x?

<main>
  <div>
    <h1>test</h1>
  </div>
</main>
main {
  outline: 1px solid red;
  overflow-y: auto;
}

div {
  margin-bottom: 2rem;
}

Solution

  • This happens because when the initial value for overflow is visible, changing either the x or y overflow value causes the other to become auto.

    The fix for me was to use this rule:

    main {
     overflow: hidden auto;
    }
    

    Posting this here because it took me way too long to figure out. Hope this helps someone.