请参阅列表项

时间:2016-10-18 14:55:32

标签: html css

有没有办法在HTML / CSS中引用有序列表的项目编号,以便在项目编号更新时更新。

即。如果下面的列表是HTML有序列表(4),请将下面第一段中的数字Log into your account自动更新为<ol>

If you already have a user account skip to step 4
1.  Create user Account
2.  Enter you personal information
3.  Click 'Create account'
4.  Log into your account
5.  Do account things...

成为以下内容,而无需手动更新第一段

If you already have a user account skip to step 5
1.  Create user Account
2.  Select your account type
3.  Enter you personal information
4.  Click 'Create account'
5.  Log into your account
6.  Do account things...

1 个答案:

答案 0 :(得分:3)

可以只使用CSS来实现它,但它需要一个hacky解决方案,surprisingly good browser support

基本上,我们的想法是使用CSS counters来计算所需列表项目的项目数(用类标记):

<div class="numbered-stuff">
  <p>
    If you want the important stuff, skip to step
  </p>
  <ol>
    <li>Stuff</li>
    <li>Stuff</li>
    <li>Stuff</li>
    <li>Stuff</li>
    <li class="important">Important Stuff</li>
    <li>Stuff</li>
  </ol>
</div>

在这种情况下,我们的第5个项目标有我们的类,所以我们需要在它之前为每个项目递增计数器:

ol {
  counter-reset: stuff;
}

ol li {
  counter-increment: stuff;
}

ol li.important:after{
  content:counter(stuff);
}

安静简单吧?现在我们只需要在文本旁边放置after元素。把它们放在一起(有点风格,因为丑陋的用户界面很糟糕):

&#13;
&#13;
@import url('https://fonts.googleapis.com/css?family=Lato');
 body,
html {
  margin: 0;
  background: #efefef;
}
.numbered-stuff {
  position: relative;
  display: inline-block;
  padding-right: 25px;
  font-family: 'Lato', sans-serif;
}
p {
  background: white;
  margin: 0;
  padding: 10px;
}
ol {
  counter-reset: stuff;
}
ol li {
  counter-increment: stuff;
}
ol li.important:after {
  content: counter(stuff);
  position: absolute;
  top: 0;
  right: 0;
  padding: 10px;
  color: white;
  background: #009688;
}
}
&#13;
<div class="numbered-stuff">
  <p>
    If you want the important stuff, skip to step
  </p>
  <ol>
    <li>Stuff</li>
    <li>Stuff</li>
    <li>Stuff</li>
    <li>Stuff</li>
    <li class="important">Important Stuff</li>
    <li>Stuff</li>
  </ol>
</div>
&#13;
&#13;
&#13;

当然,您可以根据需要更改html,但概念保持不变