Flexbox padding bottom fails in Firefox and Safari

2020-04-05 17:19发布

When scrolling down the .parent div you should see its red background at the bottom due to the padding-bottom. This works in Chrome, but not in Safari and Firefox.

.container {
  display: flex;
  width: 200px;
  height: 500px;
}

.parent {
  display: flex;
  flex-direction: column;
  background: red;
  padding-top: 20px;
  padding-bottom: 20px;
  overflow: auto;
  flex: 1;
}

.child {
  flex: 1 0 100px;
  background: green;
  border: 1px solid blue;
}
<div class="container">
 <div class="parent">
  <div class="child">
   child
  </div>
  <div class="child">
   child
  </div>
  <div class="child">
   child
  </div>
  <div class="child">
   child
  </div>
  <div class="child">
   child
  </div>
  <div class="child">
   child
  </div>
  <div class="child">
   child
  </div>
 </div>
</div>

codepen: http://codepen.io/anon/pen/NpvJPY

Edit: This question is different from the proposed duplicate because it regards a problem with a fixed padding in pixels, as opposed to the percentage padding in the duplicate.

标签: css flexbox
1条回答
混吃等死
2楼-- · 2020-04-05 17:55

I'm not exactly sure why the padding-bottom fails in Firefox and Safari. It may have something to do with the container being over-constrained. But that's just a guess.

What I am more certain about, however, is a reliable, cross-browser solution. Pseudo-elements on a flex container are rendered as flex items. So instead of padding use ::before and ::after.

.container {
  display: flex;
  width: 200px;
  height: 500px;
}

.parent {
  display: flex;
  flex-direction: column;
  background: red;
  /* padding-top: 20px; */
  /* padding-bottom: 20px; */
  overflow: auto;
  flex: 1;
}

/* NEW */
.parent::before,
.parent::after {
  flex: 0 0 20px;
  content: '';
}

.child {
  flex: 1 0 100px;
  background: green;
  border: 1px solid blue;
}
<div class="container">
  <div class="parent">
    <div class="child">child</div>
    <div class="child">child</div>
    <div class="child">child</div>
    <div class="child">child</div>
    <div class="child">child</div>
    <div class="child">child</div>
    <div class="child">child</div>
  </div>
</div>

revised codepen

查看更多
登录 后发表回答