如何在滚动元素中保持伪元素?

aur*_*rel 7 css pseudo-element css-content

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

<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>
Run Code Online (Sandbox Code Playgroud)

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

.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%;
}
Run Code Online (Sandbox Code Playgroud)

这是结果.问题是当你滚动时,:before元素也会滚动.有没有办法保持这个元素的固定.我试过不同的变化,但我不能让它工作.

谢谢

yrs*_*yre 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%;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


Mar*_*det -4

尝试这个:

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

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

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