Reputation: 3128
Having a basic HTML question. I wrote the following question:
<div class="low">
<div class="chart">
<div class="cover-fill" style="width: 91%"></div>
<div class="cover-empty" style="width: 9%"></div>
</div>
</div>
The css:
.low .chart { border: 1px solid #C21F39 }
.medium .chart { border: 1px solid #666; }
.high .chart { border: 1px solid rgb(77,146,33) }
.low .cover-fill { background: #C21F39 }
.medium .cover-fill { background: #666; }
.high .cover-fill { background: rgb(77,146,33) }
.cover-fill, .cover-empty {
display:inline-block;
height: 15px;
}
.chart {
line-height: 0;
}
.cover-full {
border-right: none !important;
}
I basically creates the following bar:
I would like to add numbers in the center of the bar itself. The wanted result is:
I tried to use the <p>
tag in the chart div
but it didn't work. What CSS should I use in order to make it work?
Upvotes: 0
Views: 620
Reputation: 27471
You can simplify your code like this:
.chart {
border: 1px solid #C21F39;
height: 15px;
background-image: linear-gradient(#C21F39, #C21F39);
background-size: var(--progress) 100%;
background-repeat: no-repeat;
text-align: center;
margin: 10px 0;
/* to center the text horizontally and vertically */
display:flex;
justify-content:center;
align-items:center;
}
<div class="chart" style="--progress:75%">text</div>
<div class="chart" style="--progress:25%">text</div>
<div class="chart" style="--progress:43%">text</div>
Center the text in filled area:
.chart {
border: 1px solid #C21F39;
height: 15px;
background-image: linear-gradient(#C21F39, #C21F39);
background-size: var(--progress) 100%;
background-repeat: no-repeat;
margin: 10px 0;
padding-right: calc(100% - var(--progress));
color: #fff;
/* to center the text horizontally and vertically */
display:flex;
justify-content:center;
align-items:center;
}
<div class="chart" style="--progress:43%">text</div>
<div class="chart" style="--progress:80%">text</div>
<div class="chart" style="--progress:20%">text</div>
I used hsl()
and some math to set background color depending on the progress.
.chart {
border: 1px solid #C21F39;
height: 15px;
--p: calc((var(--progress) / 100) * 120); /* some math to calculate hsl. reference https://coderwall.com/p/dvsxwg/smoothly-transition-from-green-to-red */
background-image: linear-gradient(to right, hsl(calc(120 - var(--p)), 100%, 50%), hsl(calc(120 - var(--p)), 100%, 50%));
background-size: calc(var(--progress) * 1%) 100%;
background-repeat: no-repeat;
margin: 10px 0;
padding-right: calc(100% - (var(--progress) * 1%));
color: #000;
/* to center the text horizontally and vertically */
display: flex;
justify-content: center;
align-items: center;
}
<div class="chart" style="--progress:100">text</div>
<div class="chart" style="--progress:80">text</div>
<div class="chart" style="--progress:20">text</div>
<div class="chart" style="--progress:50">text</div>
<div class="chart" style="--progress:5">text</div>
Upvotes: 6