有没有办法通过 CSS 获取当前目标子元素的编号?

huangapple go评论76阅读模式
英文:

Is there any way to get the number of the current targeted child with css?

问题

<div>
 <p>段落</p>
 <p>段落</p>
 <p>段落</p>
</div>

我想知道在CSS中我正在定位哪个子元素,这样我就可以做类似以下的操作:

div p:nth-child(n)::before{
 content: n + ' ';
}

输出将是:

1 段落

2 段落

3 段落


<details>
<summary>英文:</summary>

<div>
<p>paragraph</p>
<p>paragraph</p>
<p>paragraph</p>
</div>


I would like to know which child I&#39;m targeting in css, so there I can do something like:

div p:nth-child(n)::before{
content: n + ' ';
}

And the output would be

1 pagragraph

2 pagragraph

3 pagragraph


</details>


# 答案1
**得分**: 0

只使用这段CSS代码:

```css
:root {
  counter-reset: paragraph;
} 

p:after {
  content: counter(paragraph);
  counter-increment: paragraph;
}
英文:

Just use this in css:

:root {
  counter-reset: paragraph;
} 

p:after {
  content: counter(paragraph);
  counter-increment: paragraph;
}

答案2

得分: 0

Sure, here is the translated content:

:root {
  counter-reset: count;
}

p:before {
  content: counter(count) '-';
  counter-increment: count;
}
<div>
  <p>段落</p>
  <p>段落</p>
  <p>段落</p>
</div>
英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-css -->

:root {
  counter-reset: count;
} 

p:before {
  content: counter(count) &#39;-&#39;;
  counter-increment: count;
}

<!-- language: lang-html -->

&lt;div&gt;
 &lt;p&gt;paragraph&lt;/p&gt;
 &lt;p&gt;paragraph&lt;/p&gt;
 &lt;p&gt;paragraph&lt;/p&gt;
&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年1月3日 23:47:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/59581442.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定