0

I'm exploring css-variables and css calc(), so while the following code example is somewhat contrived, I'm trying to experiment with variables and calc using centering of one div withing another, which contains yet another div with the eventual goal of creating css rules that can take information from one selector rule's css-variable and using it in another sellector rule's css calc().

div {
  display: inline-block;
}

#d1a, #d1b {
  --widthD1: 100px;
  width: var( --widthD1 );
}
#d2a, #d2b {
  --widthD2: 16px;
  width: var( --widthD2 );
  background-color: yellow;
  border: thin solid black;
}
#d3a, #d3b {
  width: 100%;                                 /* width of d1a or d1b : 100px */
  background-color: lightgreen;
  border: thin solid black;
}

#d3a {
  padding-left:  calc( var( --widthD1 ) -      /* ( 100px - 16px ) 2 = 42px */
                       var( --widthD2 ) / 2 );
  padding-right: calc( var( --widthD1 ) -
                       var( --widthD2 ) / 2 );
}
#d3b {
  padding-left: 42px;
  padding-right: 42px;
}
<div id="d1a">
  <div id="d3a">
    <div id="d2a">Hi</div>
  </div>
</div>
There  -- Not what I'm trying to do!
<hr>
<div id="d1b">
  <div id="d3b">
    <div id="d2b">Hi</div>
  </div>
</div>
There  -- The desired result, except
why is the second/lower green area wider than the first/upper green area?

I realize that the this isn't the best way to center a div within a parent div.

Also, in the second example, why isn't the green area the same size as the first example's green area?

Thanks

  • you are defining `--widthD2` in a child element so its parent will not get it making the whole calc() invalid – Temani Afif Mar 23 '20 at 14:55
  • So a parent element can't use css variable created in css-rules for a child, so can't 'reformat' itself with 'knowledge' in its children's css-variable. If the variable was created in a parent or sibling then that would be OK? –  Mar 23 '20 at 15:13
  • yes a parent cannot see and will never see what is happening in a lower level which is logical because we will end having an infinite loop. If the parent need to "reformat" itself based on its child then the child need to also "reformat" itself again then the parent and .. this will never stop. CSS will go from top to bottom only once and no sibling will not work too, only parent-child relation – Temani Afif Mar 23 '20 at 15:17

0 Answers0