Home > OS >  Calculate width of a line depending on a number with a base of 50 %
Calculate width of a line depending on a number with a base of 50 %

Time:11-02

I want to increase the width of a line depending on a number (0 - 10). The width of the line should not be bigger 50 % since I set either left: 50% or right: 50% to the line to let it move to the right or left depending on a second parameter:

#line {
  height: 10px;
  background: gray;
  position: relative;
}

#line::after {
  content: '';
  height: 10px;
  display: block;
  position: absolute;
  width: 25%;
  background: red;
  right: 50%;
}
<div id="line"></div>

Within my example, I set the width to 25 % which results in an active line in the center of the left part.

Instead, I want to use CSS calc() within PHP to calculate the width by a given variable:

width: calc(50% / <?= $number ?>);

The number can hold values (stepping of 1) up to 10 which should result in a full line (50 % = 100 %) of the left part, 5 the half and so on. 0 means no width.

I'm not sure if this is possible this way? I've tried dividing them, which seems to be the right direction but not the full deal.

CodePudding user response:

calc(5% * number); should do the job:

#line {
  height: 10px;
  background: gray;
  position: relative;
}

#line::after {
  content: '';
  height: 10px;
  display: block;
  position: absolute;
  width: calc(5% * <?= $number ?>);
  background: red;
  right: 50%;
}
<div id="line"></div>

  • Related