css - 如何将伪元素固定在滚动元素中?

标签 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 元素也会滚动。有没有办法保持这个元素固定。我尝试了不同的变体,但无法使其正常工作。

谢谢

最佳答案

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

关于css - 如何将伪元素固定在滚动元素中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15721753/

相关文章:

css - 为什么不:before and :after pseudo elements work with `img` elements?

html - 使用 CSS : unexpected cells shift 正确生成表格布局

css - 有 child 和没有 child 的填充

html - css 内容字符呈现奇怪

css - 在 Joomla 的伪元素操作中添加数据库条目

html - 是否可以在 CSS `content` 中使用(多种)字体样式?

css - 在 : numbers? 之前右对齐 CSS

jquery - 如何使我的悬停标题覆盖整个图像大小?

asp.net - 母版页的相对路径让我感到困惑

html - CSS :active works incorrectly on a <a> element in IE9