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

时间:2013-03-30 18:09:19

标签: 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>

我需要将数据标记用作标题:

.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元素也会滚动。有没有办法保持这个元素的固定。我尝试了不同的变化,但我无法让它发挥作用。

由于

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:-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/