Страница на печать

Using CSS counters

CSS counters let you adjust the appearance of content based on its location in a document. For example, you can use counters to automatically number the headings in a webpage, or to change the numbering on ordered lists.

Counters are, in essence, variables maintained by CSS whose values may be incremented or decremented by CSS rules that track how many times they’re used. You can define your own named counters, and you can also manipulate the list-item counter that is created by default for all ordered lists.

Using counters

To use a counter it must first be initialized to a value with the counter-reset property. The counter’s value can then be increased or decreased using counter-increment property. The current value of a counter is displayed using the counter() or counters() function, typically within a pseudo-element content property.

Counters can only be set, reset, or incremented in elements that generate boxes. For example, if an element is set to display: none then any counter operation on that element will be ignored.

The properties of counters can be scoped to specific elements using style containment which is described in more detail in the contain property.

Manipulating a counter’s value

To use a CSS counter, it must first be initialized to a value with the counter-reset property. The property can also be used to change the counter value to any specific number.

Читайте также:  Your installed python is incomplete

Below we initialize a counter named section to the default value (0).

You can also initialize multiple counters, optionally specifying an initial value for each. Below we initialize the section and topic counters to the default value, and the page counter to 3.

counter-reset: section page 3 topic; 

Once initialized, a counter’s value can be increased or decreased using counter-increment . For example, the following declaration would increment the section counter by one on every h3 tag.

h3::before  counter-increment: section; /* Increment the value of section counter by 1 */ > 

You can specify the value to increment or decrement the counter after the counter name, using a positive or negative number.

The counter’s name must not be none , inherit , or initial ; otherwise the declaration is ignored.

Displaying a counter

The value of a counter can be displayed using either the counter() or counters() function in a content property.

For example, the following declaration uses counter() to prefix each h3 heading with the text Section : , where is the value of the count in decimal (the default display style):

h3::before  counter-increment: section; /* Increment the value of section counter by 1 */ content: "Section " counter(section) ": "; /* Display counter value in default style (decimal) */ > 

The counter() function is used when the numbering of nesting levels does not include the context of parent levels. For example, here each nested level restarts from one:

1 One 1 Nested one 2 Nested two 2 Two 1 Nested one 2 Nested two 3 Nested three 3 Three

The counters() function is used when the count for nested levels must include the count from parent levels. For example, you might use this to lay out sections as shown:

1 One 1.1 Nested one 1.2 Nested two 2 Two 2.1 Nested one 2.2 Nested two 2.3 Nested three 3 Three

The counter() function has two forms: counter() and counter(, ) . The generated text is the value of the innermost counter of the given name in scope at the pseudo-element.

The counters() function also has two forms: counters(, ) and counters(, , ) . The generated text is the value of all counters with the given name in scope at the given pseudo-element, from outermost to innermost, separated by the specified string ( ).

The counter is rendered in the specified for both methods ( decimal by default). You can use any of the list-style-type values or your own custom styles.

Examples showing the use of counter() and counters() are given below in the basic example and Example of a nested counter, respectively.

Reversed counters

A reversed counter is one that is intended to count down (decrement) rather than up (increment). Reversed counters are created using the reversed() function notation when naming the counter in counter-reset .

Reversed counters have a default initial value equal to the number of elements (unlike normal counters, which have a default value of 0). This makes it easy to implement a counter that counts from the number of elements down to one.

For example, to create a reversed counter named section with a default initial value, you would use the following syntax:

counter-reset: reversed(section); 

You can of course specify any initial value that you like.

The counter value is decreased by specifying a negative value for counter-increment .

Note: You can also use counter-increment to decrement a non-reversed counter. The main benefit of using a reversed counter is the default initial value, and that the list-item counter automatically decrements reversed counters.

List item counters

Like other counters, this has a default initial value of 0 for upward counters and «number of items» for reversed counters. Unlike author-created counters, list-item automatically increments or decrements by one for each list element, depending on whether or not the counter is reversed.

The list-item counter can be used to manipulate the default behavior of ordered lists using CSS. For example, you can change the default initial value, or use counter-increment to change the way in which the list items increment or decrement.

Examples

Basic example

This example adds «Section [the value of the counter]:» to the beginning of each heading.

CSS

body  counter-reset: section; /* Set a counter named 'section', and its initial value is 0. */ > h3::before  counter-increment: section; /* Increment the value of section counter by 1 */ content: "Section " counter(section) ": "; /* Display the word 'Section ', the value of section counter, and a colon before the content of each h3 */ > 

HTML

h3>Introductionh3> h3>Bodyh3> h3>Conclusionh3> 

Result

Basic example: reversed counter

This example is the same as the one above but uses a reversed counter. If your browser supports the reversed() function notation, the result will look like this:

reversed counter

CSS

body  counter-reset: reversed( section ); /* Set a counter named 'section', and its initial value is 0. */ > h3::before  counter-increment: section -1; /* Decrement the value of section counter by 1 */ content: "Section " counter(section) ": "; /* Display the word 'Section ', the value of section counter, and a colon before the content of each h3 */ > 

HTML

h3>Introductionh3> h3>Bodyh3> h3>Conclusionh3> 

Result

A more sophisticated example

A counter need not necessarily be shown every time it is incremented. This example counts all links with the counter showing only when a link has no text, as a convenient replacement.

CSS

:root  counter-reset: link; > a[href]  counter-increment: link; > a[href]:empty::after  content: "[" counter(link) "]"; > 

HTML

p>See a href="https://www.mozilla.org/">a>p> p>Do not forget to a href="contact-me.html">leave a messagea>!p> p>See also a href="https://developer.mozilla.org/">a>p> 

Result

Example of a nested counter

A CSS counter can be especially useful for making outlined lists, because a new instance of the counter is automatically created in child elements. Using the counters() function, separating text can be inserted between different levels of nested counters.

CSS

ol  counter-reset: section; /* Creates a new instance of the section counter with each ol element */ list-style-type: none; > li::before  counter-increment: section; /* Increments only this instance of the section counter */ content: counters(section, ".") " "; /* Combines the values of all instances of the section counter, separated by a period */ > 

HTML

ol> li>itemli> li>item ol> li>itemli> li>itemli> li>item ol> li>itemli> li>itemli> ol> ol> li>itemli> li>itemli> li>itemli> ol> li> li>itemli> ol> li> li>itemli> li>itemli> ol> ol> li>itemli> li>itemli> ol> 

Result

Specifications

Источник

Hidden HTML page counter

I have a simple HTML page and I want to add a hidden counter for that page only. Does anyone know how I can do this?

Avatar of undefined

How To Create A Hidden Hit Counter in FrontPage
http://www.webworksite.com/hitcounter.shtml

I found the urgentclick link before I posted here and tried it but it would not count the hits.

The problem with the Frontpage solution is that I am not the one that wants to look at the counter info. a non techincal person will be reviewing it and they do not have FP

They have an option for an invisible counter.

Thanks James, but I was hoping to keep this in house and just have it dump to a file or db and pull up via another webpage

I have the following code ad INDEX.PHP

/* counter */
$datei = fopen(«countlog.txt»,»r»); //opens countlog.txt to read
$count = fgets($datei,1000);
fclose($datei);
$count=$count + 1 ;

$datei = fopen(«countlog.txt»,»w»); // opens to write and deletes the old count
fwrite($datei, $count);
fclose($datei);

And to read it, I have this called ws.php

$txtfile = «countlog.txt»;
printstats ($txtfile);

$txtfile = «common/aerosch.txt»;
printstats ($txtfile);

$txtfile = «common/guestpass.txt»;
printstats ($txtfile);

function printstats ($txtfile) if ($txtfile <> «null») $Open = fopen ($txtfile, «r»);
print ($txtfile);
print (» — «);
if ($Open) $data = file ($txtfile);
for ($n = 0; $n < count($data); $n++) $GetLine = explode("\t",$data[$n]);
print («$GetLine[0]«);
>
fclose ($Open);
>
>
>
?>

Источник

HTML + CSS Нумерация страниц

Выполняя очередную рабочую ситуацию, сталкиваешься с проблемой, когда разрабатываешь или дорабатываешь CRM. На этот раз задача стояла в проставлении номера страницы.

Вариант нашелся сразу на стаке, но его отказывался понимать хром и все браузеры работающие на его движке. Даже ради такого обновил Яндекс браузер и Google Chrome, они просто проставляли на всех страницах единицы. Т.е. счет не велся. Но этот же пример работал в мозилле и в ишаке.

#content < display: table; >#pageFooter < display: table-footer-group; >#pageFooter:after

Также не работала такая конструкция:

Т.е. варианты выше подразумевают автоматическую подстановку при увелечении числа страниц на печать.

Если хром это не понимает и нужно вывести номера страниц, приходится вручную проставлять эти номера. А точнее вставлять div’ы для номеров, это дело можно сделать автоматически, но в моем случае этого не требовалось документы от силы страниц 10 были.

В итоге я создал стиль для одной страницы и в последующем его применял просто к новой, удобство заключается в том что на экране видишь, то и будет распечатано (отступы, межстрочный, номера страниц).

Раньше когда пользовался лисой на этом как-то не заморачивался. Но так как печать будет не с лисы и скорее всего без всякого обновления за последний год, то остановился на этом варианте. В целом он выглядит так:

Добавил форматы страниц А3, А5

@page < margin:0.5cm; >body < height: 100%; margin: 0px; background: rgb(204,204,204); counter-reset: pagenumber; >.page < margin: 0 auto; padding: 0px; background: white; display: block; position: relative; overflow: hidden; margin-bottom: 0.5cm; box-shadow: 0 0 0.5cm rgba(0,0,0,0.5); page-break-after: always; >.page .content < margin-top: 2cm; margin-left: 2cm; margin-right: 2cm; position: relative; height: 100%; text-indent: 1.25cm; font-size: 14px; line-height: 1.5; font-family:times new roman,times,serif; text-align: justify; overflow: hidden; >.page .content p < margin: 0em; >.page .page-footer < position: absolute; bottom: 0.5cm; left: 50%; right: 50%; >.page .page-footer:after < counter-increment: pagenumber; content: counter(pagenumber); >@media print < body, .page < margin: 0; box-shadow: 0; >> .page[size="A4"] < width: 21cm; height: 29.7cm; >.page[size="A4"][layout="portrait"] < width: 29.7cm; height: 21cm; >.page[size="A3"] < width: 29.7cm; height: 42cm; >.page[size="A3"][layout="portrait"] < width: 42cm; height: 29.7cm; >.page[size="A5"] < width: 14.8cm; height: 21cm; >.page[size="A5"][layout="portrait"]

Как пользоваться: допустим нужны 2 страницы А4 в книжной ориентации:

 
Содержимое 1 страницы

Содержимое 2 страницы

На этом все. А нет, так как делал для CRM: Клиентская база, то пожалуй расскажу как это туда засунуть для тех кто испытывает трудности:

Первое, заходим в нужную таблицу далее жмем Шаблоны печатиДобавить шаблон. Вписываете имя шаблона, формат шаблона — html, в заголовок шаблона вставляете следующий код:

     @page < margin:0.5cm; >body < height: 100%; margin: 0px; background: rgb(204,204,204); counter-reset: pagenumber; >.page < margin: 0 auto; padding: 0px; background: white; display: block; position: relative; overflow: hidden; margin-bottom: 0.5cm; box-shadow: 0 0 0.5cm rgba(0,0,0,0.5); page-break-after: always; >.page .content < margin-top: 2cm; margin-left: 2cm; margin-right: 2cm; position: relative; height: 100%; text-indent: 1.25cm; font-size: 14px; line-height: 1.5; font-family:times new roman,times,serif; text-align: justify; overflow: hidden; >.page .content p < margin: 0em; >.page .page-footer < position: absolute; bottom: 0.5cm; left: 50%; right: 50%; >.page .page-footer:after < counter-increment: pagenumber; content: counter(pagenumber); >@media print < body, .page < margin: 0; box-shadow: 0; >> .page[size="A4"] < width: 21cm; height: 29.7cm; >.page[size="A4"][layout="portrait"] < width: 29.7cm; height: 21cm; >.page[size="A3"] < width: 29.7cm; height: 42cm; >.page[size="A3"][layout="portrait"] < width: 42cm; height: 29.7cm; >.page[size="A5"] < width: 14.8cm; height: 21cm; >.page[size="A5"][layout="portrait"] < width: 21cm; height: 14.8cm; >.content table 

В тело шаблона вписываете ваш текст, например мой:

 
Содержимое 1 страницы

Содержимое 2 страницы

В Подвал шаблона вставляем логическое завершение всей конструкции :)

Кстати, не забываем про Права доступа, ибо если вы разграничили и сделали группы, без наследования, то Вам в ручную нужно их вновь проставлять. Ибо забудете, что в 90% случаях.

Источник

Оцените статью