【问题标题】:pure css stacking of position sticky without knowing component count在不知道组件数量的情况下粘贴位置的纯 css 堆叠
【发布时间】:2020-05-28 22:40:54
【问题描述】:

关于以下内容的扩展问题:

pure CSS multiple stacked position sticky?

有没有办法计算后续标题的顶部位置,以便按照示例堆叠标题。我不知道会有多少标题,所以我不能说:

.headers {position:sticky}
.header-1 {top:0;}
.header-2 {top:1em}
.header-3 {top:2em}
.header-4 {top:3em}

但需要计算差异

HTML:

<div class="container">
     <div class="headers header-1">header 1<div>
     <div class="content">This is the content<div>
     <div class="headers header-2">header 2<div>
     <div class="content">This is the content<div>
     <div class="headers header-3">header 3<div>
     <div class="content">This is the content<div>
     <div class="headers header-4">header 4<div>
     <div class="content">This is the content<div>

随着列表的增长,我需要以某种方式计算 :nth-child 或 :type-of 左右的方法。不确定是否可以在 css 中完成,但想知道是否可能

【问题讨论】:

  • 我不知道是否真的有任何方法可以根据对现有组件数量的了解来调整属性。但是,如果您关心的是在 CSS 中处理大量工作(例如您正在使用 JS 或后端进行迭代),您总是可以通过每个组件的样式标签传递一个 CSS var,并拥有一个依赖于 var 的样式规则如这里的最佳答案所示:stackoverflow.com/questions/28989708/…
  • 如果您检查您提供的链接,您会注意到有另一个链接重定向到您不需要为顶部提供值的解决方案:stackoverflow.com/a/55941740/8620333

标签: css


【解决方案1】:

如果问题是我可以使用nth-childnth-of-typen自动计算属性吗?

答案是不,你不能,至少现在是这样。

但有几种解决方法:


  • 这个不是很优雅,但它实际上是迄今为止使用最多的一个。

.bars span {
  display: block;
  height: 1em;
  margin-bottom: 1em;
  background-color: salmon;
}

.bars span:nth-child(1) {
  width: 1em;
}

.bars span:nth-child(2) {
  width: 2em;
}

.bars span:nth-child(3) {
  width: 3em;
}

.bars span:nth-child(4) {
  width: 4em;
}

// ... and many more
<div class="bars">
  <span></span>
  <span></span>
  <span></span>
  <span></span>
</div>

如果你使用的是预编译的 css,比如 scss,可以简写为:

@for $i from 1 through 20 {
  .bars span:nth-child(#{$i}) {
    width: #{$i}em;
  }
}


  • 另一个是使用css变量。但是您必须手动分配变量:

.bars span {
  display: block;
  height: 1em;
  margin-bottom: 1em;
  background-color: salmon;
}

.bars span {
  width: calc(var(--length) * 1em);
}
<div class="bars">
  <span style="--length: 1;"></span>
  <span style="--length: 2;"></span>
  <span style="--length: 3;"></span>
  <span style="--length: 4;"></span>
</div>

【讨论】:

  • 感谢在 hrml 中添加变量效果很好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 2015-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多