Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style an element based on its position within a group

I am trying to create a set of boxes. I want to try and see if I can set the size of the box based on its position within the group.

Currently this is possible if I know the number of boxes beforehand and use the :nth-child() selector and the appropriate position.

Since CSS already has the capability to find the position of the element in the group, is it possible to use this positioning as an input for the size.

So for example something like

#boxes:nth-child() {
    height:calc(n * 10);
    width:calc(n * 10);
}

This purpose can easily be achieved using a server side code or even Javascript but just curious to understand if we can use CSS to achieve this, using calc or any other feature.

like image 935
skv Avatar asked May 30 '16 14:05

skv


People also ask

Which selector is used to style elements based on its state?

Combinator selectors (select elements based on a specific relationship between them) Pseudo-class selectors (select elements based on a certain state)

What is used to specify a style for group of elements in CSS?

In CSS, selectors are used to target the HTML elements on our web pages that we want to style.

Which selector is used to apply a style to a particular group of elements?

CSS class selector The class selector selects HTML elements that have a class attribute that matches the selector. The class selector is useful for targeting multiple elements, things like cards or images that you want to have matching styles. To select an element with a specific class, you use a .

Which positioning property in CSS makes elements to be moved around within their parent element?

Absolute positioning In contrast, an element that is absolutely positioned is taken out of the flow; thus, other elements are positioned as if it did not exist. The absolutely positioned element is positioned relative to its nearest positioned ancestor (i.e., the nearest ancestor that is not static ).


2 Answers

In CSS Selectors Level 3, there are no methods for targeting an element then, using variables corresponding to that element's position within a group, tailoring styles for that element.

In CSS, the calc() function does not allow variables. Only mathematical expressions with addition (+), subtraction (-), multiplication (*), and division (/) are allowed as component values.

With Sass, however, a CSS preprocessor, using variables in a calc() function is possible.

References:

  • CSS Selectors Level 3
  • 8.1. Mathematical Expressions: calc()
  • Sass Variable in CSS calc() function
  • Sass Variables
like image 107
Michael Benjamin Avatar answered Oct 26 '22 06:10

Michael Benjamin


You can't do this in pure css, but you can with scss. For example:

@for $i from 1 through 5 {
  .box:nth-child(#{$i}) {
     height: 50px * $i;
   }
}

You can play with code here.

like image 27
RusAndreev Avatar answered Oct 26 '22 04:10

RusAndreev