Home > other >  reference specific value inside of a class?
reference specific value inside of a class?

Time:08-17

i'm trying to reference one part of a class in order to calculate something in another part of the code. i only want to reference the dimensions, nothing else. below, you will see cobra's dimensional information is blank. i'm choosing arbitrary numbers and calculations - just trying to make it slightly "complicated" enough to explain a bit more. i hope this makes sense:

  • i want cobra's width to equal viper's width divided by 2.
  • i want cobra's height to equal viper's height exactly.
  • i want to be able to only change viper's information and have
    cobra automatically update because it references viper
    .
.viper
 {
    width: calc((100px - 50px) * 3) / 2);
    height: 200px;
    font-family: garamond;
    font-color: black;

 }

.cobra
  {
    width:
    height:
    font-family: georgia;
    font-color: blue;
  }

CodePudding user response:

If you are trying to accomplish this with JUST CSS, this can be accomplished quite easily using CSS variables.

First declare your viper's width and height as a basis for a snake:

 :root{
  --viper-width: calc(((100px - 50px) * 3) / 2);
  --viper-height: 200px;
 }

Then you give this variable to the equivalent properties of your snakes that you wish to modify in relation to the viper.

.cobra{
  width: calc(var(--viper-width) / 2);
  height: var(--viper-height);
  font-family: georgia;
  color: blue;
}

Then, any time you change your --viper-width and --viper-height variables, your .cobra will adjust accordingly.

CodePudding user response:

You can use CSS variables, but note that you have a couple of errors in your code.

font-color does not exist, use color.

The calc has a missing opening bracket.

This snippet corrects these and puts the viper height and width into the root so that these CSS variables can be used anywhere in the document (given cobra and viper are not related).

:root {
  --viperW: calc(((100px - 50px) * 3) / 2);
  --viperH: 200px;
}

.viper {
  width: var(--viperW);
  height: var(--viperH);
  font-family: garamond;
  color: black;
  background-color: pink;
}

.cobra {
  width: calc(var(--viperW) / 2);
  height: var(--viperH);
  font-family: georgia;
  color: blue;
  background-color: cyan;
}
<div >Viper</div>
<div >Cobra</div>

  • Related