learningjavascriptks learningjavascriptks - 1 month ago 6
CSS Question

is it possible to reference a css property from another element?

I am introducing myself in CSS, it's like a structure of a javaScript object, somehow in this code I want to use class of .blm height property on my keyframes' border-bottom-width property, this is the code and demo



.blm {
display: inline-block;
background-color: pink;
border: solid black 1px;
height: 300px;
width: 100px;
animation: kk 3s linear 0s 2 normal;
box-sizing: border-box;
}
@keyframes kk {
0% {
border-bottom-color: red;
border-bottom-width: 0px;
}
100% {
border-bottom-color: red;
border-bottom-width: 300px;/* I want this to reference on .blm height property and maybe use percentage in it*/
}
}
.blm2 {
border: sold black 1px;
width: 100px;
height: 100px;/* also here, if this isn't child element */
background: green;
}

<div class="blm">
blm
</div>
<div class="blm2">
blm2
</div>




Answer

The only way to do this, currently, is to use css variables (which are not supported in IE or Edge):

:root {
  --shared-height: 300px;
}

.blm {
  display: inline-block;
  background-color: pink;
  border: solid black 1px;
  height: var(--shared-height);
  width: 100px;
  animation: kk 3s linear 0s 2 normal;
  box-sizing: border-box;
}

@keyframes kk {
  0% {
    border-bottom-color: red;
    border-bottom-width: 0px;
  }
  100% {
    border-bottom-color: red;
    height: var(--shared-height);
    /* i want this to reference  on .blm height property and maybe use percentage in it*/
  }
}

/* provides the default styles for the element unless
   the subsequent selector is more specific: */
.blm2 {
  border: sold black 1px;
  width: 100px;
  background: green;
  height: var(--shared-height);
}

/* if the .blm2 element has a specific ancestor
   (the obviously-named '.ancestorElementSelector')
   then this height will be used: */
.ancestorElementSelector .blm2 {
  height: 100px;
  /* also here, if this isn't child element */
}

CSS pre-processors, such as SASS and LESS (among others, presumably), allow the use of variables, but compile to regular CSS after they've been compiled.

These may be worth exploring, particularly if Edge or IE are required, but since I've never felt the need to use them I can't recommend them explicitly.

Comments