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.
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.
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.
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.
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.
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
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With