Automatic Figure Numbering with CSS Counters


Содержание

CSS counters – automatic numbering before h2

CSS counters are variables maintained by CSS whose values may be incremented by CSS rules to track how many times they are used. Here is code flow on how css counters can be used to count h2 tags.

  • Reset counter using counter-reset: mycounter . It can be done using body style.
  • Increment counter using counter-increment: mycounter on occurrence of an h2 tag. To increment value by more that 1, you can use counter-increment: mycounter 2 .
  • Display counter using ::before and content property of h2 tag.

CSS Counters

Pizza

Hamburger

Hotdogs

CSS counters are «variables» maintained by CSS whose values can be incremented by CSS rules (to track how many times they are used). Counters let you adjust the appearance of content based on its placement in the document.

Automatic Numbering With Counters

CSS counters are like «variables». The variable values can be incremented by CSS rules (which will track how many times they are used).

To work with CSS counters we will use the following properties:

  • counter-reset — Creates or resets a counter
  • counter-increment — Increments a counter value
  • content — Inserts generated content
  • counter() or counters() function — Adds the value of a counter to an element

To use a CSS counter, it must first be created with counter-reset .

The following example creates a counter for the page (in the body selector), then increments the counter value for each

element and adds «Section :» to the beginning of each

element:

Example

h2::before <
counter-increment: section;
content: «Section » counter(section) «: «;
>

Nesting Counters

The following example creates one counter for the page (section) and one counter for each

element (subsection). The «section» counter will be counted for each

element with «Section .», and the «subsection» counter will be counted for each

element with » . «:

Example

h1 <
counter-reset: subsection;
>

h1::before <
counter-increment: section;
content: «Section » counter(section) «. «;
>

h2::before <
counter-increment: subsection;
content: counter(section) «.» counter(subsection) » «;
>

A counter can also be useful to make outlined lists because a new instance of a counter is automatically created in child elements. Here we use the counters() function to insert a string between different levels of nested counters:

Example

ol <
counter-reset: section;
list-style-type: none;
>

li::before <
counter-increment: section;
content: counters(section,».») » «;
>


Wrong numbering with css counters

Why the following css doesn’t get correct numbering of sections (http://jsfiddle.net/75MHS/)? When I put h3 and h4 inside div s, all chapter numbers and section numbers are always one. But when I remove div containers, the numbers are all correct.

4 Answers 4

The reason it works as intended in the second section (without the div’s) but doesn’t in the fist section is due to counter scope. According to the W3C:

The scope of a counter starts at the first element in the document that has a ‘counter-reset’ for that counter and includes the element’s descendants and its following siblings with their descendants.

In the second half of the html, the h3 s and h4 s are siblings, therefore, the counter-reset defined on the h3 applies to the following h4 siblings. In the first part of the html, the h4 s are not descendants nor siblings of the h3 s, therefore, the counter-rest has no effect on them since they’re out of scope.

The other thing is, if counter-reset is not defined in a given scope, it assumes a value of 0 each time you counter-increment or refer to the counter in a content rule, which explains why you’re getting all 1 s in the first part of the html:

If ‘counter-increment’ or ‘content’ on an element or pseudo-element refers to a counter that is not in the scope of any ‘counter-reset’, implementations should behave as though a ‘counter-reset’ had reset the counter to 0 on that element or pseudo-element.

If you have to wrap things in divs, I would:

Define a counter-reset for the chapters counter on body , so that it’s not assumed 0 each time you use a counter-increment .

Either nest the h4 s under their parent h3 s (which is not cool) or make them siblings to ensure they’re in the right scope.

Automatic caption numbering knitr hooks for figures and tables

These function implement ideas by Max Gordon and DeanK (see Details) to add knitr hooks to automate the numbering of figures and tables when generating R Markdown documents.

Arguments

The name of the caption, used in the knitr chunk options to provide the caption text.

The string in which to add the number of the figure or table. The text ‘%s’ will be replaced by the number.

Optionally, a css class to pass to the HTML element that surrounds the .

Optionall, a css class to pass to the HTML element.

Any css style to pass to the figure element directly (‘inline’).

Any css style to pass to the image element directly (‘inline’).

The name of the option to use to retrieve and set the counter. This can be used, for example, to have multiple caption types use the same counter.

If not NULL and numeric, the counter will start at this number.

Details

The figure caption function is basically the one designed by Max Gordon (see http://gforge.se/2014/01/fast-track-publishing-using-knitr-part-iii/.

Value


Nothing is returned; the correct hooks are configured for knitr .

Automatic Heading Numbers with CSS

Introduction

I’ve played around with automatic heading numbering before but always thought it needed to be done thgrough scripting. I only found out this week (from Ivan Herman) that you can do it with CSS. Not only that, it’s been around for years (it’s in CSS 2.1). Ah well, you learn something new every day.

What Am I Trying To Do?

I want to create a CSS file that I can link to that will automatically number headings and not have to think about it — include a link to the stylesheet and it should «just do it.»

Constraint: start at h2

I use h1 for the title of the page and I always make the content of h1 match the title element — so that should not be part of the numbering. The first heading to be numbered should therefore be the first h2 element.

Constraint: make it possible switch numbering off for a given heading

There are some circumstances in which it’s useful to be able to include a heading that isn’t part of the numbering so we need to be able to switch it off. Looking at what others have done the usual way is to define a class of nocount .

So for demonstration purposes, here’s an h3 that doesn’t increment the counter.

This heading has no number

And switch it back on again …

This heading has a number

And picks up where the previous numbered one left off.

Constraint: it needs to work across all 6 levels

HTML5 defines 6 levels of heading (i.e. h1 through h6 ) so I need to make a single CSS file that will cover the extreme, rarely encountered in my life so far but it could happen, case where a document used all those levels and numbered them.

Here’s an h4

Here’s an h5
Here’s an h6

Just a quick check — everything still working as it should?

Here’s another h4

Here’s another h5
Here’s another h6

What Am I not trying to do?

In this case, I don’t want to style the headings — that’s a separate task. This is just about the numbers.

And what about section elements?

I really like the section element that HTML5 introduces, as well as aside , header , footer etc. and I generally use them. The algorithm for defining the outline numbering is part of the HTML5 spec and the Mozilla Developer pages are really good on this. Personally, I have trained myself to make sure I use headings at the right level so, unless I make a mistake, I’ll only use an h4 within the scope of an h3 . That said, I will usually preceed each heading with a section element. I believe the idea of always beginning a section with an h1 element has lost favour — good, because that seemed to lead to the need to define all sorts of extra CSS just to make an h1 look like the h3 you actually meant it to be.

Bottom line: I fully understand the usefulness of sections but, for this exercise, I’m going to ignore them and just focus on the h n elements.

The CSS

Time to actually put the CSS on show:

If the W3C spec is too dense (and I admit they generally are), then David Storey provides a good explanation in his article Automatic numbering with CSS Counters and little is served by my repeating his explanation. Basically you first define your counters (by resetting them) and then you increment and insert them as generated content using the :before psuedo class.


Watch the cascade!

I wanted to use as few lines of CSS as possible so I first tried this:

See why that doesn’t work? It’s the C in CSS — the cascade. You’re provding a series of different values for the same property and each one replaces the other so that in fact the only counter that gets reset here is the last one.

Advanced Autonumbering Techniques with CSS Counters

Autonumbering is quite a useful feature. Basically, it means that as long as you keep adding new elements, each new element is getting an ordered number. Right now, you are probably all like — ‘Aye aye, Captain Obvious! This feature has been around since, like, forever! Why bother writing an article about it?’

Well, yes. You are right, numbered lists are a living HTML classic. But there’s more to it.

This post will give you some idea how autonumbering can be used in a wider range of tasks. The trick is in the CSS counters we are going to use here. The corresponding properties let you control autonumbering directly from CSS, and, thus, give you more freedom and open new possibilities for list usage.

Further, we will provide you with code examples for each autonumbering solution, as well as with a couple of awesome style ideas.

Pictures Autonumbering In Online Documentation

When you are planning on adding lots of images to a help topic (or just any web page for that matter) things can get complicated. Pure frustration is accidentally skipping one picture when adding a capture with a number or just mixing up numbers. Such mistakes are easy to miss, and they cause a lot of trouble when it comes to fixing them. There’s a solution — set capture autonumbering up with CSS:

The code is quite simple, the solution is based on the counters:

    Create a new CSS >That’s it. Each div element with this class assigned will be numbered automatically!

Autonumbering Nested Lists

Nested lists are quite common in user guides and software manuals. They are perfect to describe and systemize massive chunks of data. Nested lists can have as many levels as you wish as long as it makes sense. They can be created following different numbering patterns, and, also, nested lists can combine both ordered and unordered lists.

Take a look at this example:

On the screenshot above, we have three levels of elements. Here’s the HTML code we used:

And, again, we have CSS counters to rule them all:

What we did there is we switched off the default list style and reset the count for each section of the

    tag. And, then, we just set the desired counters format for the
    tag. Each time you open the
      tag, the count starts anew.

    That’s it, one more use case is at your service!

    Headings Autonumbering

    Numbering headings is always a great idea. Navigation is essential, so we’re gonna have to rock it.

    Headings are represented by the

    , etc. tags in HTML.

    is usually the title, so it won’t need any numbering. Cuz it’s the one and only:

    So, this is how some basic heading structure looks. We have a couple of

    tags and a nested

    tag. The HTML is super easy:

    Now, take a look at the CSS code. It might look scary, but we’ll restore your courage by explaining it further.

    And here is the explanation, as promised:

      We set the counter-reset property for each parent element to start counting from

    because

    is our title, and it needs no counter. If we wanted to have it counted too, we’d start by resetting it in the body section instead of


    .
    We reset the counter for

    twice — in the body section and in the

    tag just to be on the safe s >To number headings, we didn’t create any class. This means that all the headings we described in CSS will be numbered by default. In the example below, you can see that we have the ability to switch autonumbering off for some elements:

    The HTML code for our example is:

    So, basically, we have this

    subsection that we do not want numbered. As a rule, this can be some introduction or conclusion.

    Now, let’s walk the talk. If you need to switch off numbering for some specific headings:

    • Create a new >noncount.
    • Assign this >And voila! Customizing is awesome ;)

    Styling Ordered List Numbers With CSS

    Now, when you know how to set up different kinds of autonumbering elements, it’s time for you to learn some more CSS styling. Below, you’ll find several style examples that you can use and modify to match your documentation design and color palette.

    Style List Numbers With Circles

    This list design is quite basic, but it really makes your lists stand out against other text.

    To use this style, do the following:

      Create a new >Try playing around with other properties to get things to look right for your particular case.

    Style List Numbers With Borders

    This design is a bit more complex. But If you follow the steps below, it will be just as easy to implement as the previous one.

    To use this style for your numbered list, follow these steps:

      Create a new >The counters are tough, but you made it! Feel free to use any code examples you see in this article.

    You have learned A LOT today, so be proud of yourself and good luck with implementing these advanced autonumbering techniques in your documentation!

    This article was written based on our own technical writing experience. If you need to create online documentation, you may also like ClickHelp — the best user documentation tool for web developers.

    12 Generated content , automatic numbering , and lists

    Note: Several sections of this specification have been updated by other specifications. Please, see «Cascading Style Sheets (CSS) — The Official Definition» in the latest CSS Snapshot for a list of specifications and the sections they replace.

    The CSS Working Group is also developing CSS level 2 revision 2 (CSS 2.2).

    In some cases, authors may want user agents to render content that does not come from the document tree. One familiar example of this is a numbered list; the author does not want to list the numbers explicitly, he or she wants the user agent to generate them automatically. Similarly, authors may want the user agent to insert the word «Figure» before the caption of a figure, or «Chapter 7» before the seventh chapter title. For audio or braille in particular, user agents should be able to insert these strings.

    In CSS 2.1, content may be generated by two mechanisms:

    • The ‘content’ property, in conjunction with the :before and :after pseudo-elements.
    • Elements with a value of ‘list-item’ for the ‘display’ property.

    12.1 The :before and :after pseudo-elements

    Authors specify the style and location of generated content with the :before and :after pseudo-elements. As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element’s document tree content. The ‘content’ property, in conjunction with these pseudo-elements, specifies what is inserted.

    For example, the following rule inserts the string «Note: » before the content of every P element whose «class» attribute has the value «note»:

    The formatting objects (e.g., boxes) generated by an element include generated content. So, for example, changing the above style sheet to:

    would cause a solid green border to be rendered around the entire paragraph, including the initial string.


    The :before and :after pseudo-elements inherit any inheritable properties from the element in the document tree to which they are attached.

    For example, the following rules insert an open quote mark before every Q element. The color of the quote mark will be red, but the font will be the same as the font of the rest of the Q element:

    In a :before or :after pseudo-element declaration, non-inherited properties take their initial values.

    So, for example, because the initial value of the ‘display’ property is ‘inline’, the quote in the previous example is inserted as an inline box (i.e., on the same line as the element’s initial text content). The next example explicitly sets the ‘display’ property to ‘block’, so that the inserted text becomes a block:

    The :before and :after pseudo-elements interact with other boxes as if they were real elements inserted just inside their associated element.

    For example, the following document fragment and style sheet:

    . would render in exactly the same way as the following document fragment and style sheet:

    Similarly, the following document fragment and style sheet:

    . would render in exactly the same way as the following document fragment and style sheet:

    Note. This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.

    12.2 The ‘content’ property

    ‘content’

captionName
figure_counter_str, table_counter_str
figureClass
figureInlineStyle
imgInlineStyle
optionName
resetCounterTo
Value: normal | none | [ | | | attr( ) | open-quote | close-quote | no-open-quote | no-close-quote ]+ | inherit
Initial: normal
Applies to: :before and :after pseudo-elements
Inherited: no
Percentages: N/A
Media: all
Computed value: On elements, always computes to ‘normal’. On :before and :after, if ‘normal’ is specified, computes to ‘none’. Otherwise, for URI values, the absolute URI; for attr() values, the resulting string; for other keywords, as specified.

This property is used with the :before and :after pseudo-elements to generate content in a document. Values have the following meanings:

none The pseudo-element is not generated. normal Computes to ‘none’ for the :before and :after pseudo-elements. «> Text content (see the section on strings). «> The value is a URI that designates an external resource (such as an image). If the user agent cannot display the resource it must either leave it out as if it were not specified or display some indication that the resource cannot be displayed. «> Counters may be specified with two different functions: ‘counter()’ or ‘counters()’. The former has two forms: ‘counter( name )’ or ‘counter( name , style )’. The generated text is the value of the innermost counter of the given name in scope at this pseudo-element; it is formatted in the indicated style (‘decimal’ by default). The latter function also has two forms: ‘counters( name , string )’ or ‘counters( name , string , style )’. The generated text is the value of all counters with the given name in scope at this pseudo-element, from outermost to innermost separated by the specified string. The counters are rendered in the indicated style (‘decimal’ by default). See the section on automatic counters and numbering for more information. The name must not be ‘none’, ‘inherit’ or ‘initial’. Such a name causes the declaration to be ignored. open-quote and close-quote These values are replaced by the appropriate string from the ‘quotes’ property. no-open-quote and no-close-quote Introduces no content, but increments (decrements) the level of nesting for quotes. attr(X) This function returns as a string the value of attribute X for the subject of the selector. The string is not parsed by the CSS processor. If the subject of the selector does not have an attribute X, an empty string is returned. The case-sensitivity of attribute names depends on the document language.

The ‘display’ property controls whether the content is placed in a block or inline box.

The following rule causes the string «Chapter: » to be generated before each H1 element:

Authors may include newlines in the generated content by writing the «\A» escape sequence in one of the strings after the ‘content’ property. This inserted line break is still subject to the ‘white-space’ property. See «Strings» and «Characters and case» for more information on the «\A» escape sequence.

Generated content does not alter the document tree. In particular, it is not fed back to the document language processor (e.g., for reparsing).

12.3 Quotation marks

In CSS 2.1, authors may specify, in a style-sensitive and context-dependent manner, how user agents should render quotation marks. The ‘quotes’ property specifies pairs of quotation marks for each level of embedded quotation. The ‘content’ property gives access to those quotation marks and causes them to be inserted before and after a quotation.

12.3.1 Specifying quotes with the ‘quotes’ property


‘quotes’

Value: [ ]+ | none | inherit
Initial: depends on user agent
Applies to: all elements
Inherited: yes
Percentages: N/A
Media: visual
Computed value: as specified

This property specifies quotation marks for any number of embedded quotations. Values have the following meanings:

none The ‘open-quote’ and ‘close-quote’ values of the ‘content’ property produce no quotation marks. [ «> «> ]+ Values for the ‘open-quote’ and ‘close-quote’ values of the ‘content’ property are taken from this list of pairs of quotation marks (opening and closing). The first (leftmost) pair represents the outermost level of quotation, the second pair the first level of embedding, etc. The user agent must apply the appropriate pair of quotation marks according to the level of embedding.

For example, applying the following style sheet:

to the following HTML fragment:

would allow a user agent to produce:

while this HTML fragment:

Note. While the quotation marks specified by ‘quotes’ in the previous examples are conveniently located on computer keyboards, high quality typesetting would require different ISO 10646 characters. The following informative table lists some of the ISO 10646 quotation mark characters:

Character Approximate rendering ISO 10646 code (hex) Description
» » 0022 QUOTATION MARK [the ASCII double quotation mark]
0027 APOSTROPHE [the ASCII single quotation mark]
203A SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
« « 00AB LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
» » 00BB RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
` 2020 LEFT SINGLE QUOTATION MARK [single high-6]
2020 RIGHT SINGLE QUOTATION MARK [single high-9]
« 201C LEFT DOUBLE QUOTATION MARK [double high-6]
» 201D RIGHT DOUBLE QUOTATION MARK [double high-9]
,, 201E DOUBLE LOW-9 QUOTATION MARK [double low-9]

12.3.2 Inserting quotes with the ‘content’ property

Quotation marks are inserted in appropriate places in a document with the ‘open-quote’ and ‘close-quote’ values of the ‘content’ property. Each occurrence of ‘open-quote’ or ‘close-quote’ is replaced by one of the strings from the value of ‘quotes’ , based on the depth of nesting.


‘Open-quote’ refers to the first of a pair of quotes, ‘close-quote’ refers to the second. Which pair of quotes is used depends on the nesting level of quotes: the number of occurrences of ‘open-quote’ in all generated text before the current occurrence, minus the number of occurrences of ‘close-quote’. If the depth is 0, the first pair is used, if the depth is 1, the second pair is used, etc. If the depth is greater than the number of pairs, the last pair is repeated. A ‘close-quote’ or ‘no-close-quote’ that would make the depth negative is in error and is ignored (at rendering time): the depth stays at 0 and no quote mark is rendered (although the rest of the ‘content’ property’s value is still inserted).

Note. The quoting depth is independent of the nesting of the source document or the formatting structure.

Some typographic styles require open quotation marks to be repeated before every paragraph of a quote spanning several paragraphs, but only the last paragraph ends with a closing quotation mark. In CSS, this can be achieved by inserting «phantom» closing quotes. The keyword ‘no-close-quote’ decrements the quoting level, but does not insert a quotation mark.

The following style sheet puts opening quotation marks on every paragraph in a BLOCKQUOTE, and inserts a single closing quote at the end:

This relies on the last paragraph being marked with a class «last».

For symmetry, there is also a ‘no-open-quote’ keyword, which inserts nothing, but increments the quotation depth by one.

12.4 Automatic counters and numbering

Automatic numbering in CSS 2.1 is controlled with two properties, ‘counter-increment’ and ‘counter-reset’ . The counters defined by these properties are used with the counter() and counters() functions of the the ‘content’ property.

‘counter-reset’

Value: [ ? ]+ | none | inherit
Initial: none
Applies to: all elements
Inherited: no
Percentages: N/A
Media: all
Computed value: as specified

‘counter-increment’

Value: [ ? ]+ | none | inherit
Initial: none
Applies to: all elements
Inherited: no
Percentages: N/A
Media: all
Computed value: as specified

The ‘counter-increment’ property accepts one or more names of counters (identifiers), each one optionally followed by an integer. The integer indicates by how much the counter is incremented for every occurrence of the element. The default increment is 1. Zero and negative integers are allowed.

The ‘counter-reset’ property also contains a list of one or more names of counters, each one optionally followed by an integer. The integer gives the value that the counter is set to on each occurrence of the element. The default is 0.

The keywords ‘none’, ‘inherit’ and ‘initial’ must not be used as counter names. A value of ‘none’ on its own means no counters are reset, resp. incremented. ‘Inherit’ on its own has its usual meaning (see 6.2.1). ‘Initial’ is reserved for future use.

This example shows a way to number chapters and sections with «Chapter 1», «1.1», «1.2», etc.

If an element increments/resets a counter and also uses it (in the ‘content’ property of its :before or :after pseudo-element), the counter is used after being incremented/reset.

If an element both resets and increments a counter, the counter is reset first and then incremented.

If the same counter is specified more than once in the value of the ‘counter-reset’ and ‘counter-increment’ properties, each reset/increment of the counter is processed in the order specified.

The following example will reset the ‘section’ counter to 0:

The following example will increment the ‘chapter’ counter by 3:

The ‘counter-reset’ property follows the cascading rules. Thus, due to cascading, the following style sheet:

will only reset ‘imagenum’. To reset both counters, they have to be specified together:

12.4.1 Nested counters and scope

Counters are «self-nesting», in the sense that resetting a counter in a descendant element or pseudo-element automatically creates a new instance of the counter. This is important for situations like lists in HTML, where elements can be nested ins >

Thus, the following suffices to number nested list items. The result is very similar to that of setting ‘display:list-item’ and ‘list-style: inside’ on the LI element:

The of a counter starts at the first element in the document that has a ‘counter-reset’ for that counter and includes the element’s descendants and its following siblings with their descendants. However, it does not include any elements in the scope of a counter with the same name created by a ‘counter-reset’ on a later sibling of the element or by a later ‘counter-reset’ on the same element.

If ‘counter-increment’ or ‘content’ on an element or pseudo-element refers to a counter that is not in the scope of any ‘counter-reset’ , implementations should behave as though a ‘counter-reset’ had reset the counter to 0 on that element or pseudo-element.

In the example above, an OL will create a counter, and all children of the OL will refer to that counter.

If we denote by item[n] the n th instance of the «item» counter, and by «<" and ">» the beginning and end of a scope, then the following HTML fragment will use the indicated counters. (We assume the style sheet as given in the example above).

Another example, showing how scope works when counters are used on elements that are not nested, is the following. This shows how the style rules given above to number chapters and sections would apply to the markup given.

The ‘counters()’ function generates a string composed of all of the counters with the same name that are in scope, separated by a given string.

The following style sheet numbers nested list items as «1», «1.1», «1.1.1», etc.

12.4.2 Counter styles


By default, counters are formatted with decimal numbers, but all the styles available for the ‘list-style-type’ property are also available for counters. The notation is:

for the default style, or:

All the styles are allowed, including ‘disc’, ‘circle’, ‘square’, and ‘none’.

12.4.3 Counters in elements with ‘display: none’

An element that is not displayed ( ‘display’ set to ‘none’) cannot increment or reset a counter.

For example, with the following style sheet, H2s with class «secret» do not increment ‘count2’.

Pseudo-elements that are not generated also cannot increment or reset a counter.

For example, the following does not increment ‘heading’:

Elements with ‘visibility’ set to ‘hidden’, on the other hand, do increment counters.

12.5 Lists

CSS 2.1 offers basic visual formatting of lists. An element with ‘display: list-item’ generates a principal block box for the element’s content and, depending on the values of ‘list-style-type’ and ‘list-style-image’, possibly also a marker box as a visual indication that the element is a list item.

The describe basic visual formatting of lists: they allow style sheets to specify the marker type (image, glyph, or number), and the marker position with respect to the principal box (outside it or within it before content). They do not allow authors to specify distinct style (colors, fonts, alignment, etc.) for the list marker or adjust its position with respect to the principal box; these may be derived from the principal box.

‘list-style-type’

Value: disc | circle | square | decimal | decimal-leading-zero | lower-roman | upper-roman | lower-greek | lower-latin | upper-latin | armenian | georgian | lower-alpha | upper-alpha | none | inherit
Initial: disc
Applies to: elements with ‘display: list-item’
Inherited: yes
Percentages: N/A
Media: visual
Computed value: as specified

This property specifies appearance of the list item marker if ‘list-style-image’ has the value ‘none’ or if the image pointed to by the URI cannot be displayed. The value ‘none’ specifies no marker, otherwise there are three types of marker: glyphs, numbering systems, and alphabetic systems.

Glyphs are specified with disc , circle , and square . Their exact rendering depends on the user agent.

Numbering systems are specified with:

decimal Decimal numbers, beginning with 1. decimal-leading-zero Decimal numbers padded by initial zeros (e.g., 01, 02, 03, . 98, 99). lower-roman Lowercase roman numerals (i, ii, iii, iv, v, etc.). upper-roman Uppercase roman numerals (I, II, III, IV, V, etc.). georgian Traditional Georgian numbering (an, ban, gan, . he, tan, in, in-an, . ). armenian Traditional uppercase Armenian numbering.

Alphabetic systems are specified with:

lower-latin or lower-alpha Lowercase ascii letters (a, b, c, . z). upper-latin or upper-alpha Uppercase ascii letters (A, B, C, . Z). lower-greek Lowercase classical Greek alpha, beta, gamma, . (α, β, γ, . )

This specification does not define how alphabetic systems wrap at the end of the alphabet. For instance, after 26 list items, ‘lower-latin’ rendering is undefined. Therefore, for long lists, we recommend that authors specify true numbers.

CSS 2.1 does not define how the list numbering is reset and incremented. This is expected to be defined in the CSS List Module [CSS3LIST] .

For example, the following HTML document:

might produce something like this:

The list marker alignment (here, right justified) depends on the user agent.

‘list-style-image’

Value: | none | inherit
Initial: none
Applies to: elements with ‘display: list-item’
Inherited: yes
Percentages: N/A
Media: visual
Computed value: absolute URI or ‘none’

This property sets the image that will be used as the list item marker. When the image is available, it will replace the marker set with the ‘list-style-type’ marker.

The size of the image is calculated from the following rules:

    If the image has a intrinsic w >

The following example sets the marker at the beginning of each list item to be the image «ellipse.png».

‘list-style-position’

Value: ins >inherit
Initial: outs > Applies to: elements with ‘display: list-item’
Inherited: yes
Percentages: N/A
Media: visual
Computed value: as specified

This property specifies the position of the marker box with respect to the principal block box. Values have the following meanings:

outside The marker box is outs >’overflow’ is other than ‘visible’. (This is expected to change in the future.) The size or contents of the marker box may affect the height of the principal block box and/or the height of its first line box, and in some cases may cause the creation of a new line box. Note: This interaction may be more precisely defined in a future level of CSS. inside The marker box is placed as the first inline box in the principal block box, before the element’s content and before any :before pseudo-elements. CSS 2.1 does not specify the precise location of the marker box.

The above example may be formatted as:


In right-to-left text, the markers would have been on the right side of the box.

‘list-style’

Value: [ || || ] | inherit
Initial: see indiv > Applies to: elements with ‘display: list-item’
Inherited: yes
Percentages: N/A
Media: visual
Computed value: see individual properties

The ‘list-style’ property is a shorthand notation for setting the three properties ‘list-style-type’ , ‘list-style-image’ , and ‘list-style-position’ at the same place in the style sheet.

Although authors may specify ‘list-style’ information directly on list item elements (e.g., «li» in HTML), they should do so with care. The following rules look similar, but the first declares a descendant selector and the second a (more specific) child selector.

Authors who use only the descendant selector may not achieve the results they expect. Consider the following rules:

The desired rendering would have level 1 list items with ‘lower-alpha’ labels and level 2 items with ‘disc’ labels. However, the cascading order will cause the first style rule (which includes specific class information) to mask the second. The following rules solve the problem by employing a child selector instead:

Another solution would be to specify ‘list-style’ information only on the list type elements:

Inheritance will transfer the ‘list-style’ values from OL and UL elements to LI elements. This is the recommended way to specify list style information.

A URI value may be combined with any other value, as in:

In the example above, the ‘disc’ will be used when the image is unavailable.

A value of ‘none’ within the ‘list-style’ property sets whichever of ‘list-style-type’ and ‘list-style-image’ are not otherwise specified to ‘none’. However, if both are otherwise specified, the declaration is in error (and thus ignored).

For example, a value of ‘none’ for the ‘list-style’ property sets both ‘list-style-type’ and ‘list-style-image’ to ‘none’:

The result is that no list-item marker is displayed.

CSS counters

Одной из редко используемых возможностей CSS2.1 являются счетчики. Описаны они в разделе спецификации, посвященной генерации контента. Что же это такое?

Приведу пример из спецификации, эмулирующий обычный нумерованый список с помощью счетчика и свойства content:

Первым правилом мы назначаем элементам OL счетчик с именем «item», затем для всех LI меняем значение свойства display на block, вместо значения по умолчанию (list-item), чем отключаем стандартные маркеры-цифры. Наконец, в последнем правиле, мы инкрементируем счетчик для каждого элемента списка, а само его значение показываем перед элементом c помощью функции counter() и свойства content. Всё просто.

С помощью механизма счетчиков можно делать нумерованые списки, с нумерацией 1, 1.1, 1.2. Причем сами маркеры можно оформлять достаточно гибко например в результате вот такого кода:

ol >
li > item 1, level 1 li >
li > item 2, level 1 li >
li > item 3, level 1 li >
li > item 4, level 1
ol >
li > item 1, level 2 li >
li > item 2, level 2 li >
li > item 3, level 2 li >
ol >
li >
li > item 5, level 1 li >
ol >

* This source code was highlighted with Source Code Highlighter .

мы получим вот такой список:

Функция counters() принимает два параметра, имя счетчика, значение которого нужно вывести и строку-разделитель между значениями вложенных счетчиков, в данном случае это точка. Также вторым параметром можно указывать любое из возможных значений атррибута list-style-type, т.е. none, disc, circle и square. В последних трех случаях список станет выглядеть так же как обычный ненумерованный список с маркерами соответствующего типа.

Но и это еще не всё

style >
div /* объявляем счетчик num-p */
div p /* для каждого p внутри div инкрементируем его */
div:after < /* выводим результат */
display:block;font-weight:bold;
content: «Всего абзацев: » counter(num-p) «.»;
>
style >
div >
p > Абзац 1 p >
p > Абзац 2 p >
p > Абзац 3 p >
p > Абзац 4 p >
div >

* This source code was highlighted with Source Code Highlighter .

станет вот такая страница:

Здесь мы воспользовались псевдоэлементом :after элемента div, для вывода конечного значения привязанного к нему счетчика.

Ну и наконец приведу код, результат которого вы видели на изображении в самом начале топика, если вы подключите этот стиль в качестве пользовательского стиля вашего браузера, то возле каждого топика у вас появится «немного статистики» о нем:

/* Инициализируем счетчики */
div.hentry <
counter-reset:
num-post-sections 1
/* Количество заголовков/секций в топике. Обратите внимание, что счетчику можно передать начальное значение. */
/* В данном случае это единица, потому что один заголовок уже есть вне блока .content */
num-code-listings /* Листинги кода code и pre */
num-bq /* цитаты */
num-br /* break-lines */
num-links /* ссылки */
num-links-internal /* внутренние ссылки */
num-links-rel-tag /* ссылки тэгов rel=’tag’ */
num-img /* изображения */
;
>
/* Инкрементируем счетчики. */
div.hentry .content h4,
div.hentry .content h5,
div.hentry .content h6 < counter-increment: num-post-sections; >
div.hentry .content code,
div.hentry .content pre < counter-increment: num-code-listings; >
div.hentry .content img < counter-increment: num-img; >
div.hentry .content blockquote < counter-increment: num-bq; >
div.hentry .content br

div.hentry .content a[href] < /* все ссыкли */
counter-increment: num-links;
>
div.hentry .content a[href^=»http://habrahabr.ru/»],
div.hentry .content a[href^=»/»] < /* внутренние ссыкли */
counter-increment:
num-links
num-links-internal;
>
div.hentry a[rel=»tag»] < /* теги */
counter-increment:
num-links
num-links-rel-tag;
>
/* Показываем результат счетчиков */
div.hentry:after <
clear:both;
display: block;
background:#9cc;
border:1px solid #79B1D4;
padding:10px;
margin:0 35px;
white-space:pre;
content:
«This topic contains: \a»
«Sections — » counter(num-post-sections) «,\a»
«Code listings — » counter(num-code-listings) «,\a»
«Links — » counter(num-links) «, » counter(num-links-internal) » internal and »
counter(num-links-rel-tag)» tags, \a»
«Images — » counter(num-img) «,\a»
«Quotes — » counter(num-bq) «,\a»
«Break lines — » counter(num-br) «\a»
;
>

* This source code was highlighted with Source Code Highlighter .

Ограничения


1. К сожалению, всеми нами горячо и страстно любимый браузер Intenet Explorer — не поддерживает CSS-счетчики вплоть до версии 7, как и свойство content. Но в 8-й, говорят поддержка будет.
2. Вывод суммарных счетчиков возможен только в псевдоэлементе :after, что ограничивает возможности дизайна.
3. Контент, сгенеренный с помощью css не может быть выбран/выделен пользователем.

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

Upd. В написании топика и кода сильно помогла статья Meitar Moscovitz, там есть еще неплохие примеры.

Automatic caption numbering knitr hooks for figures and tables

These function implement ideas by Max Gordon and DeanK (see Details) to add knitr hooks to automate the numbering of figures and tables when generating R Markdown documents.

Arguments

The name of the caption, used in the knitr chunk options to provide the caption text.

The string in which to add the number of the figure or table. The text ‘%s’ will be replaced by the number.

Optionally, a css class to pass to the HTML element that surrounds the .

Optionall, a css class to pass to the HTML element.

Any css style to pass to the figure element directly (‘inline’).

Any css style to pass to the image element directly (‘inline’).

The name of the option to use to retrieve and set the counter. This can be used, for example, to have multiple caption types use the same counter.

If not NULL and numeric, the counter will start at this number.

Details

The figure caption function is basically the one designed by Max Gordon (see http://gforge.se/2014/01/fast-track-publishing-using-knitr-part-iii/.

Value

Nothing is returned; the correct hooks are configured for knitr .

CSS | Counters

Counters in CSS are basically variables which can be used for numbering and values of CSS counters may be incremented by CSS rules. For example, CSS counters can be used to increment the numbering of the headings automatically. In HTML,

    tag is used to give the ordered numbers to list items but CSS contains counter to give order elements in some other fashion.

CSS counters properties: CSS counters contains the following properties:

  • counter-reset: It is used to reset a counter.
  • counter-increment: It basically increments a counter value.
  • content: It is used to generate content.
  • counter() or counters() function: The value of a counter can be displayed using either the counter() or counters() function in a content property. These two functions basically used to add the value of a counter to the element.

Initialization the CSS Counter: To use CSS counter property firstly it must be created with the counter-reset property and the first step is resetting the counter. The myCounter by default initialized to a value 0(zero) with the counter-reset property.
Syntax:

Incrementation and Use of CSS Counter: To incrementing the counter use CSS counter-increment property.
Syntax:

The counter() or counters() function in a content is used to display the content in a particular order.
Syntax:

Цукерберг рекомендует:  Проверка доступности имени пользователя на PHP и Ajax
Понравилась статья? Поделиться с друзьями:
Все языки программирования для начинающих
captionName
figure_counter_str, table_counter_str
figureClass
figureInlineStyle
imgInlineStyle
optionName
resetCounterTo