元素设置了overflow后,内容右边不能实现边距

2021.11.24 1,669 0

大家在写前端布局时,会不会遇到一个问题,当你设置了父元素overflow-y:auto,并且设置内左右内边距padding: 0 20px;内容滚动到最后,右边距失效。这个跟你写布局结构有关系,我们来看看如何解决这一问题。

写法一

这种写法,代码量多点,能够兼容Chrome/Safari/Edge/Firefox


--html--

<div class="case">
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
        <li>9</li>
        <li>10</li>
        <li>11</li>
        <li>12</li>
        <li>13</li>
        <li>14</li>
        <li>15</li>
    </ul>
</div>

--style--

.case {
  display         : flex;
  margin          : 0 auto;
  width           : 100%;
  background-color: white;
  overflow-y      : auto;

  ul {
    display: flex;
    padding: 0 20px;

    li {
      width           : 100px;
      height          : 100px;
      line-height     : 100px;
      text-align      : center;
      background-color: cornsilk;

      &:nth-child(even) {
        background-color: bisque;
      }
    }
  }
}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

写法二

往往这种写法会出现兼容问题,Chrome正常显示,Safari失效,手机端同样也有问题,所以我们需要做一些处理。往下看


--html--

<div class="case2">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
    <div>9</div>
    <div>10</div>
    <div>11</div>
    <div>12</div>
    <div>13</div>
    <div>14</div>
    <div>15</div>
</div>

--style--

.case2 {
  width           : 100%;
  display         : flex;
  margin          : 0 auto;
  padding-left    : 20px;
  overflow-y      : auto;
  background-color: white;

  div {
    flex            : 0 0 auto;
    width           : 100px;
    height          : 100px;
    line-height     : 100px;
    text-align      : center;
    background-color: cornsilk;
    margin-right    : 20px;

    &:nth-child(even) {
      background-color: bisque;
    }
  }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15


解决方法

在父元素中加入伪元素 :after 来处理


--style--

.case2 {
  width           : 100%;
  display         : flex;
  margin          : 0 auto;
  padding-left    : 20px;
  overflow-y      : auto;
  background-color: white;

  div {
    flex            : 0 0 auto;
    width           : 100px;
    height          : 100px;
    line-height     : 100px;
    text-align      : center;
    background-color: cornsilk;
    margin-right    : 20px;

    &:nth-child(even) {
      background-color: bisque;
    }
  }

  // Add
  &::after {
    content: '';
    padding-right: 0.02px;
  }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
400

全部评论 0


    抢沙发