如果滚动条的宽度是固定的(300px),并且文本的宽度(文本,而不是元素)或多或少是固定的(大约85px – 从1%到100%),请将文本设置为绝对定位的伪元素.progress的子项,并设置它的宽度和最大宽度:
width: calc(100% + 100px);
max-width: 300px;
如果将文本右对齐,它将显示在条形后面,直到达到最大宽度.
/** js to demonstrate changing values **/
var progressBar = document.querySelector('.progress');
function progress() {
var minmax = [0,100];
var step = 1;
const iterate = (current) => {
progressBar.style.width = `${current}%`;
progressBar.setAttribute('data-percentage',current);
if(current !== minmax[1]) {
setTimeout(() => iterate(current + step),40);
} else {
minmax = minmax.reverse();
step = -step;
setTimeout(() => iterate(minmax[0]),500);
}
}
iterate(minmax[0]);
}
progress();
section#progressish {
padding: 20px;
width: 300px;
}
div#progressbar {
background-color: #d1d1d1;
height: 10px;
margin-bottom: 15px;
width: 100%;
}
div#progressbar>.progress[data="bar"] {
position: relative;
background-color: #111111;
height: 10px;
margin-bottom: 15px;
width: 0%;
}
.progress::before {
position: absolute;
top: -20px;
width: calc(100% + 85px);
max-width: 300px;
text-align: right;
white-space: nowrap;
content: attr(data-percentage)"% avklarat";
}