Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set CSS padding to value based on attribute

Tags:

css

attr

This doesn't work:

li[depth="3"] { padding-left: calc(40px * attr(depth integer)); }

However, this works:

li[depth="3"] { padding-left: calc(40px * 3); }

Apparently attr(name type) is not supported inside calc()... yet.

  • More information here: On attr() and calc()

Is there any way to replace the following CSS with CSS that works for all integer values of attribute depth?

li[depth="2"] { padding-left:  40px; }
li[depth="3"] { padding-left:  80px; }
li[depth="4"] { padding-left: 120px; }
like image 631
Leftium Avatar asked Oct 30 '22 16:10

Leftium


1 Answers

There is no special CSS that could achieve this - typically it's best to avoid referencing style/layout rules in the DOM. The CSS flexbox model could prove useful for this purpose, to allow the elements to size according to how many of them exist.

If you needed to go the CSS route you specified, a preprocessor like Sass could allow you to automate the writing of all that code with a loop (example below in SCSS syntax) - though note that the final .css file produced will have all the rules compiled out. Also note that the range here is limited - you can adjust 20 to any amount but it won't work infinitely (though I assume it won't even reach 20 given the example).

@for $i from 1 to 20 {
  li[depth="#{$i}"] { padding-left: #{($i - 1) * 40px}; }
}
like image 156
Jon Uleis Avatar answered Nov 15 '22 07:11

Jon Uleis