我希望使用以下HTML样式,以便章节编号按顺序1、2、3排列,即使第三个数字位于与前两个不同的列表中。
<!DOCTYPE html>
<title>Continued Numbering</title>
<style>
ol.book-contents li {
list-style-type: upper-roman;
}
ol.book-contents ol li {
list-style-type: decimal;
}
</style>
<ol class="book-contents">
<li>Section One
<ol>
<li>Chapter One</li>
<li>Chapter Two</li>
</ol>
</li>
<li>Section Two
<ol>
<li>Chapter Three</li>
</ol>
</li>
</ol>也就是说,我希望输出如下所示:
I. Section One
1. Chapter 1
2. Chapter 2
II. Section Two
3. Chapter 3我能用CSS做这件事吗?
发布于 2021-12-23 21:58:21
这里有一个完整的解决方案,它使用counter-reset、counter-increment和content属性来解决连续的数字问题,并使用::marker伪元素来解决格式化问题。归功于单身汉的::marker想法。不需要在HTML中添加额外的标记(超出了最初问题中指定的book-contents类)。
正如您在测试中所看到的那样,这个CSS处理麻烦的第十章,(1)它的多位章节编号在小数点上正确地对齐,(2)它的长名称与适当的挂起的缩进包在一起。
ol.book-contents {
counter-reset: chapter;
}
ol.book-contents li {
list-style-type: upper-roman;
}
ol.book-contents li ol li {
list-style-type: decimal;
counter-increment: chapter;
}
ol.book-contents li ol li::marker {
content: counter(chapter) '. ';
}<!DOCTYPE html>
<title>Continued Numbering</title>
<ol class="book-contents">
<li>Section One
<ol>
<li>Chapter One</li>
<li>Chapter Two</li>
</ol>
</li>
<li>Section Two
<ol>
<li>Chapter Three</li>
<li>Chapter Four</li>
<li>Chapter Five</li>
<li>Chapter Six</li>
<li>Chapter Seven</li>
<li>Chapter Eight</li>
<li>Chapter Nine</li>
<li>Chapter Ten (shown so you can see its proper decimal alignment and its proper long-string wrapping behavior that honors the hanging indent)</li>
</ol>
</li>
</ol>
发布于 2021-12-31 20:04:37
您可以使用CSS计数器将自定义列表编号保持在相同的级别。
基本上,您设置了3个主要的CSS属性。
counter-reset: keyword -当您需要启动一个新列表时,您可以通过关键字(子列表-计数器)来维护一个计数器。将其视为定义计数器的变量。counter-increment: keyword -在您的元素呈现上,每当选择器元素/伪元素在DOM中呈现时,使用关键字递增计数器content: counter(keyword) -访问计数器的当前值使用::在伪元素之前,可以为用例定义自己的列表样式,并将ol上的列表样式设置为none。
body {
counter-reset: sublist-counter; /* Set a counter named 'section', and its initial value is 0. */
}
ol.sublist{
list-style:none;
padding-left: 10px;
}
ol.sublist > li::before {
counter-increment: sublist-counter;
content: counter(sublist-counter) ". ";
}<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<ol class="book-contents">
<li>Section One
<ol class="sublist">
<li>Chapter One</li>
<li>Chapter Two</li>
</ol>
</li>
<li>Section Two
<ol class="sublist">
<li>Chapter Three</li>
</ol>
</li>
</ol>
</body>
</html>
发布于 2021-12-24 00:29:18
有可能使用ol属性为计数start创建偏移量,如
<ol start="3">在你的情况下
ol.book-contents li {
list-style-type: upper-roman;
}
ol.book-contents ol li {
list-style-type: decimal;
}<ol class="book-contents">
<li>Section One
<ol>
<li>Chapter One</li>
<li>Chapter Two</li>
</ol>
</li>
<li>Section Two
<ol start="3">
<li>Chapter Three</li>
<li>Chapter Four</li>
</ol>
</li>
</ol>
https://stackoverflow.com/questions/70466973
复制相似问题