【问题标题】:How to keep a pseudo-element fixed within a scrolled element?如何将伪元素固定在滚动元素中?
【发布时间】:2025-12-27 04:45:12
【问题描述】:

我怎样才能得到这个效果:

<pre class="default prettyprint prettyprinted" data-codetitle="homepage.html" style=""><code>
body{
  position: relative; 
  @include background(linear-gradient(left, lighten($me, 11%), lighten($me, 11%) 
    $half, $darkbackground $half, $darkbackground));
  color: $text;
  width: 100%;
  height: 100%;
  @include breakpoint(baby-bear) {
    @include background(linear-gradient(left, lighten($me, 11%), lighten($me, 11%) 
    45%, $darkbackground 45%, $darkbackground));
  }
}
</span></code></pre>

我需要使用数据标签作为标题:

.prettyprint {
    margin: 0 0 0 0.5%;
    border-left: 2px solid #ce8f80;
    overflow: auto;
    position: relative;
    width: 300px;
}
.prettyprint:before {
    content: attr(data-codetitle);
    background: #ce8f80;
    display: block;
    width: 100%;
}

这是result。问题是当您滚动时,:before 元素也会滚动。有没有办法保持这个元素固定。我尝试了不同的变体,但我无法让它发挥作用。

谢谢

【问题讨论】:

    标签: css pseudo-element css-content


    【解决方案1】:

    对于支持position: sticky的浏览器

    .prettyprint {
      margin: 0 0 0 0.5%;
      border-left: 2px solid #ce8f80;
      overflow: auto;
      position: relative;
      width: 300px;
    }
    
    .prettyprint:before {
      position: sticky;
      left: 0;
      content: attr(data-codetitle);
      background: #ce8f80;
      display: block;
      width: 100%;
    }
    <pre class="default prettyprint prettyprinted" data-codetitle="homepage.html" style="">
      <code>
            body{
              position: relative; 
              @include background(linear-gradient(left, lighten($me, 11%), lighten($me, 11%) 
              $half, $darkbackground $half, $darkbackground));
              color: $text;
              width: 100%;
              height: 100%;
              @include breakpoint(baby-bear) {
                @include background(linear-gradient(left, lighten($me, 11%), lighten($me, 11%) 
                45%, $darkbackground 45%, $darkbackground));
              }
            }
      </code>
    </pre>

    【讨论】:

      【解决方案2】:

      试试这个:

      .prettyprint:before {
          content: attr(data-codetitle);
          background: #ce8f80;
          display: block;
          position: fixed;
          width: inherit;
      }
      

      设置position: fixed 使元素不跟随滚动,然后设置width: inherit 使伪元素与父元素保持相同的宽度。

      小提琴参考:http://jsfiddle.net/audetwebdesign/r8aNC/2/

      【讨论】:

      • 固定定位将元素附加到视口,而不是相对父级。
      • @AdmireNL 您在这一点上是正确的。在我的小提琴中,内容并没有导致页面滚动,所以我没有注意到副作用。我会再看一遍。