如何在滚动元素内固定伪元素?

8
我该如何获得这种效果:
<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>

我需要将data标签用作标题:
.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%;
}

这是结果。问题在于当您滚动时,:before元素也会滚动。有没有办法使此元素保持固定。我尝试了不同的变化,但无法使其正常工作。
谢谢
2个回答

5

对于支持 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>


-4

试试这个:

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

设置position: fixed以使元素不随滚动而移动,然后设置width: inherit以使伪元素与父元素具有相同的宽度。

Fiddle参考:http://jsfiddle.net/audetwebdesign/r8aNC/2/


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接