I am looking for a purely CSS solution to the following problem.
I have a div that contains an indeterminate number of divs, I am looking for a given RGB color, for example, (0,0,0)
and a range of opacity values to (0.3 - 0.7)
vary the opacity of the divs in that range progressively.
At the moment I have the following. Using the selectors first-child
and last-child
:
.container {
background : #f7f7f7;
padding : 10px;
}
.container div {
height : 30px;
margin : 5px;
background : rgba(0, 0, 0, .5);
}
.container div:first-child {
background : rgba(0, 0, 0, .3);
}
.container div:last-child {
background : rgba(0, 0, 0, .7);
}
<div class="container">
<div>aaa</div>
<div>aaa</div>
<div>aaa</div>
<div>aaa</div>
<div>aaa</div>
<div>aaa</div>
</div>
Is it possible using only CSS?
CSS works with selectors, it is impossible to do calculations or iterations, the closest thing would be to use 'nth-child' to refer to a child of an element.
But in this way you must statically specify the opacity value, not randomly, if the children of the container element contain more children in turn, these will be affected, so that it only applies to the immediately lower children then
to get what you want you must necessarily use Javascript to give the opacity a random value and additionally to use a loop where you assign the opacity to 'n' number of children.
With SASS or LESS you can use iterators but in the end this generates CSS so you're restricted to the number of iterations you specify in the preprocessor so you'll end up with the same thing.
With a certain number it can be done, exceeding the number the color is maintained. a clear example is a breadcrumb:
The key is to speculate the amount of element that we are going to use, in your example we could insert this code:
Using the directive
@for
in Sass you can achieve this byCSS
(preprocessing):See an example