Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set margin (indent) based on counter value in CSS

Tags:

css

I'm wondering whether it is possible to set the element margin-left based on the value of a counter, using CSS3.

In other words, having a HTML like this:

<section>A</section>
<section>B</section>
<section>C</section>

have first block with a margin-left: 0em, second one with 1em and so on.

So far, I have tried the following:

section
{
    counter-increment: sect-indent;
    margin-left: calc(counter(sect-indent) * 1em);
}

But it seems that calc() doesn't support getting counter values.

Is such a thing possible using CSS3? I'm not interested in solutions involving ECMAScript.

like image 657
Michał Górny Avatar asked Nov 17 '12 12:11

Michał Górny


People also ask

Can I use counter CSS?

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.

What is counter-increment CSS?

The counter-increment property increases or decreases the value of one or more CSS counters. The counter-increment property is usually used together with the counter-reset property and the content property. Default value: none.

How do you use margin 0 auto?

margin:0 auto; 0 is for top-bottom and auto for left-right. It means that left and right margin will take auto margin according to the width of the element and the width of the container. Generally if you want to put any element at center position then margin:auto works perfectly.

How does margin-left auto work?

margin-left: auto; The auto keyword will give the left side a share of the remaining space. When combined with margin-right: auto , it will center the element, if a fixed width is defined.


2 Answers

It only works inside the content property, not like a variable the way you are thinking of it. If you view it in DevTools or the like, it's not an integer. You'd still see counter(myCounter) in there.

"In CSS 2.1, the values of counters can only be referred to from the 'content' property." source

like image 173
Jason Lydon Avatar answered Sep 28 '22 00:09

Jason Lydon


For a Small Set

If you are dealing with a small set of section elements next to each other (as your sample shows), then using the adjacent sibling selector (or nth-of-type if only CSS3 support is desired) will get you what you want without counting. However, probably much more than about five elements and the css could get too cumbersome, so if you are looking at this for hundreds of elements, it is not practical.

section { margin-left: 0}
section + section {margin-left: 1em}
section + section + section {margin-left: 2em}
like image 44
ScottS Avatar answered Sep 28 '22 01:09

ScottS