Оформляем «ol»
Дата публикации: 01.11.2011
Задача
Оформить нумерованный список на свое усмотрение. Например, нужно цвет цифр сделать отличным от цвета текста, или эти цифры заключить в какую-то рамку и т.д. и т.п.

Решение
Нам помогут CSS свойства counter-reset, counter-increment и псевдоэлемент before.
HTML код выглядит обычно:
<ol> <li>текст...</li> <li>текст...</li> </ol>
CSS тоже достаточно прост:
.main ol {
list-style: none; /* убираем дефорлтные цифры */
counter-reset: point; /* задаем переменную для счетчика */
}
.main ol li {
margin-bottom: 10px;
padding-left: 25px;
position: relative;
}
.main ol li:before {
content: counter(point); /* выводим значение переменной */
counter-increment: point 1; /* увеличваем счетчик на 1 */
font-size: 11px; /* декор цифр */
position: absolute;
left: 0;
top: 6px;
background: #FF0000;
width: 20px;
padding: 3px 0;
color: #fff;
font-weight: bold;
text-align: center;
}
Для IE6-7 потребуется костыль, т.е. ни CSS счетчики, ни псевдоэлементы не поддерживаются:
.main ol {
z-index: expression(
runtimeStyle.zIndex = 1,
function(node) {
var list = node.childNodes, i = list.length;
while(i--) {
if(list[i].nodeType == 1) {
list[i].insertAdjacentHTML('afterBegin', '<div>'+(i+1)+'</div>');
}
}
}(this));
)
}
.main ol div {
font-size: 11px;
position: absolute;
left: 0;
top: 6px;
background: #FF0000;
width: 20px;
padding: 3px 0;
color: #fff;
font-weight: bold;
text-align: center;
}
Живой пример. Проверено:
- IE 7-9
- Firefox 7
- Opera 11.5
- Chrome
Чтобы закрепить работу счетчиками, реализуем следующую задачу:

Пояснения:
- нумерация первого уровня в списке состоит из двух частей: номер главы и номер раздела;
- нумерация главы начинается с 12;
- нумерация подразделов состоит из трех частей: глава.раздел.подраздел.
<ol id="myLists">
<li>The :before and :after pseudo-elements</li>
<li>The &content& property</li>
<li>Quotation marks
<ol>
<li>Specifying quotes with the 'quotes' property</li>
<li>Inserting quotes with the 'content' property </li>
</ol>
</li>
[...]
</ol>
id у списка нужен для IE6-7.
.main ol {
padding: 10px;
list-style: none;
}
.main ol li:before { /* общие стили для псевдолементов */
font-size: 11px;
position: absolute;
left: 0;
top: 3px;
}
.main {
counter-reset: chapter 12; /* устанавливаем счетчик текущей главы */
}
.main>ol {
border: 2px solid #66FF00;
counter-reset: section; /* устанавливаем счетчик раздела */
}
.main>ol ol {
counter-reset: subsection; /* устанавливаем счетчик подраздела */
}
.main ol li {
margin-bottom: 10px;
padding-left: 35px;
position: relative;
}
.main ol li ol li {
padding-left: 45px;
}
.main>ol li:before {
content: counter(chapter)"."counter(section); /* нумерация раздела состоит из двух частей: [глава.раздел] */
counter-increment: section; /* увеличиваем счетчик раздела */
color: red;
top: 3px;
padding: 0;
}
.main>ol li ol li:before {
content: counter(chapter)"."counter(section)"."counter(subsection); /* нумерация подраздела состоит из трех частей: [глава.раздел.подраздел] */
counter-increment: subsection; /* увеличиваем счетчик подраздела */
color: #FF6600;
}
Стили для IE7:
.main ol li div {
font-size: 11px;
position: absolute;
left: 0;
top: 3px;
}
.main>ol li div {
color: red;
}
.main>ol li ol li div {
color: #FF6600;
}
Т.к. логика тут достаточно сложная, я не рискнул ее реализовывать через expression:
function decimalList()
{
var chapter = 12,
section = 1,
list = document.getElementById("myLists").childNodes,
lenLiFirstLevel = list.length;
for(i=0;i<lenLiFirstLevel;i++)
{
list[i].insertAdjacentHTML('afterBegin', '<div>'+chapter+'.'+section+'</div>');
if(list[i].getElementsByTagName("ol").length!=0)
{
var subList = list[i].getElementsByTagName("ol")[0].childNodes,
subListLen = subList.length,
subSection = 1;
for(j=0;j<subListLen;j++)
{
subList[j].insertAdjacentHTML('afterBegin', '<div>'+chapter+'.'+section+'.'+subSection+'</div>');
subSection++;
}
}
section++;
}
return;
}
window.onload = decimalList;
Живой пример. Проверено:
- IE 7-9
- Firefox 7
- Opera 11.5
- Chrome
По теме
- Индивидуальные стили для li. Избавляемся от классов.
- Эмуляция псевдоэлементов after и before для IE 6-7
Теги: оформление контента, списки
Показать комментарии
