- Html progress bar color
- How to Set Color of Progress Bar using HTML and CSS?
- What is a Progress Bar?
- Creating Progress Bar Using HTML
- Example 1
- Create a basic progress bar Using HTML
- Styling the Progress Bar
- Example 2
- Create progress bar Using HTML and CSS
- Adding Text to the Progress Bar
- Example 3
- Create progress with additional information bar Using CSS
- Conclusion
- Create a custom-styled progress bar with Pure CSS and HTML
- Styling the progress
- Accent color
- Non-standard styling
- Pseudo-elements
- Cross-browser friendly solution
- Animating a progress bar with CSS
- Demo
- Кастомизация HTML5 progress element
Html progress bar color
Наш чат в Telegram для обмена идеями, проектами, мыслями, людьми в сфере ИТ г.Ростова-на-Дону: @it_rostov
Тег является индикатором хода выполнения задачи. Например, загрузки файла или процента проголосовавших к определенному времени.
Атрибуты тега
Должно выполняться неравенство:
Числовое значение value можно менять с помощью JavaScript.
Внешний вид элемента зависит от операционной системы и браузера.
.default-progressbar progress Выполнено 0% работы
Браузеры, не отображающие тег выводят текст из контейнера .
CSS-стили элемента можно изменять. Для этого сначала надо отменить стили браузеров по умолчанию.
Изменение цвета фона элемента
/* Firefox */ progress < background: #fac; >/* Chrome */ progress::-webkit-progress-bar
Изменение цвета значения элемента
Opera 11 и 12 не допускает изменение цвета индикатора – он остается зеленым.
/* IE10 */ progress < color: #e0a; >/* Firefox */ progress::-moz-progress-bar < background: #e0a; >/* Chrome */ progress::-webkit-progress-value
Градиент в качестве значения
Для Internet Explorer цвет значения задается свойством color, т.е. никакого градиента для IE не получится 🙁
.gradient-progressbar progress < appearance: none; -moz-appearance: none; -webkit-appearance: none; border: none; margin-top: 10px; background: #eee; border: 0; width: 100%; height: 25px; border-radius: 9px; color: #9c3; >.gradient-progressbar progress::-webkit-progress-bar < background: #eeeeee; border-radius: 9px; >.gradient-progressbar progress::-webkit-progress-value < background: linear-gradient(to bottom, #cf9 0%, #9c3 100%); border-radius: 9px; >.gradient-progressbar progress::-moz-progress-bar Выполнено 50% работы
How to Set Color of Progress Bar using HTML and CSS?
In web development, a progress bar is an important part of the website. A progress bar displays the progress of the process. With the help of it, the user can see the status of the work being done on the website, which includes loading time, file uploads, file downloads and other similar tasks. By default, it looks gray. However, to make the progress bars stand out and look visually appealing, their color can be changed using HTML and CSS.
What is a Progress Bar?
A progress bar is used to show the progress of a task. It is a graphical user interface element. It basically consists of a horizontal bar that fills up gradually as the task progresses, accompanied by a percentage value or other indicator of completion. Progress bars are used in web applications to provide feedback to users about how long it will take to complete a process such as a file upload, file download, or software installation.
Creating Progress Bar Using HTML
HTML markup is used to create progress bars. A progress bar is created in HTML5 using the element. Here is an example of how to create a basic progress bar using HTML −
In the above example, we have created a progress bar, and to show the progress bar as 30% complete, the value attribute is set to 30. The max attribute is set to 100.
Example 1
Below is a full code example to creating basic progress bar using HTML
bodyCreate a basic progress bar Using HTML
Styling the Progress Bar
After creating the progress bar, we can use the CSS to style it and set its color. CSS provides the ::-webkit-progress-value pseudo-element to developers to set the color of the progress bar. Here is an example to apply the CSS style on a progress bar.
progress < width: 300px; height : 25px; border: 2px solid gray; >progress::-webkit-progress-bar < background-color: green; >progress::-webkit-progress-value
We target both the ::-webkit-progress-bar and ::-webkit-progress-value pseudo-elements and set their background colors. And we also set the height and width of the progress bar by targeting the element.
Example 2
Below is a full code example to create a progress bar using HTML and CSS.
body < text-align: center; >progress < width: 300px; height: 25px; border: 2px solid gray; >progress::-webkit-progress-bar < background-color: green; >progress::-webkit-progress-valueCreate progress bar Using HTML and CSS
Adding Text to the Progress Bar
Additional information is provided to users by adding text to the progress bar. To do this, we use the ::-webkit-progress-bar pseudo-element and the ::-webkit-progress-value pseudo-element to create two layers, with the progress value layer on top of the progress bar layer. For example −
progress < position: absolute; height: 24px; width: 300px; border: 1px solid #fff; >progress::before < content: "Loading: " attr(value) "%"; position: absolute; width: 100%; text-align: center; font-size: 18px; color: blue; >progress::-webkit-progress-bar < background-color: orange; >progress::-webkit-progress-value
In the example above, we have added a ::before pseudo-element to the element. It will display the progress value as text on top of the progress bar. We have also fixed the text in the center of the progress bar and set its font size to 18px.
Example 3
Below is a full code example of adding the text to the progress bar.
progress < position: absolute; height: 24px; width: 500px; border: 1px solid #fff; >progress::before < content: "Loading: " attr(value) "%"; position: absolute; width: 100%; text-align: center; font-size: 18px; color: blue; >progress::-webkit-progress-bar < background-color: orange; >progress::-webkit-progress-valueCreate progress with additional information bar Using CSS
Conclusion
Here, we have discussed that a progress bar is a valuable tool for web development. It provides feedback to the users on the progress of the work being done on the website. It can also be customized to better match the overall design of the website.
Create a custom-styled progress bar with Pure CSS and HTML
A progress bar is a nice way to showcase the completion state of something. The default HTML element looks inconsistent across different browsers. Fortunately, there’s a way to give a custom style for the progress bar element.
To display a progress bar a progress tag is used, along with some attributes. The max attribute represents the maximum value of the progress bar. The value attribute represents the current value of the progress element.
Default progress bar appearance across different browsers:
If no value attribute is specified the progress element will show up with the loading animation:
Styling the progress
Accent color
You can set the color of the current progress by defining the accent-color property.
progress accent-color: coral; >
The accent-color property is a new thing and can be used to style form elements as well. However, at the time this article is written, it is lacking full browser support. So you shouldn’t rely on it much right now, but worth knowing about this property, to use it in the future.
Non-standard styling
Currently, there are some non-standard pseudo-elements available to style the progress tag parts. It is recommended not to use these selectors in production as the behavior is not consistent and may change in the future. But it’s worth knowing that these kinds of properties exist.
For these properties to work, first thing you’ll need to set the appearance of the progress element to none .
progress -webkit-appearance: none; >
The first one is the ::-webkit-progress-bar pseudo-element. It represents the entire progress element. You can use it to set the background color. Will only work in browsers based on Blink or WebKit.
::-webkit-progress-bar background-color: aliceblue; >
To style the actual value use the ::-webkit-progress-value selector for Blink or WebKit based browsers and ::-moz-progress-bar for Firefox browser.
::-webkit-progress-value background-color: coral; > ::-moz-progress-bar background-color: coral; >
Pseudo-elements
The progress element can also be styled with pseudo-elements, ::before representing the background and ::after representing the progress bar. However, pseudo-elements for the progress element are not supported by all browsers (Safari and Firefox don’t have support).
progress position: relative; > progress::before, progress::after content: ""; position: absolute; top: 0; left: 0; height: 100%; > progress::before width: 100%; background: burlywood; > progress::after width: 75%; background: brown; >
Cross-browser friendly solution
To make the progress bar look and behave the same way in all browsers you’ll need to wrap it in a div . The div will replace the appearance of the progress bar.
class="progress-container"> value="75" max="100">75%
First, you need to hide the progress element by setting its opacity to 0.
Then, add the desired styles to the div . If you want it to take up the same width as the progress element, set the display property to inline-block . Otherwise, the div will span 100% of the container, and its width should be controlled via width property.
.progress-container position: relative; display: inline-block; background: #eee; height: 20px; border-radius: 6px; overflow: hidden; >
To display the progress value we’ll use the ::before pseudo-element.
.progress-container::before content: ""; position: absolute; top: 0; left: 0; height: 100%; width: 75%; background: turquoise; >
For the progress bar to be more descriptive let’s add a label and a numeric value. The p tag will represent the label, and its pseudo-element will display a numeric value.
class="progress-element"> class="progress-label">HTML class="progress-container"> max="100" value="75">75%
.progress-label position: relative; > .progress-label::after content: "75%"; position: absolute; top:0; right: 0; >
Animating a progress bar with CSS
If you want to animate progress value on page load, you can add a CSS animation to the pseudo-element.
First, let’s create a keyframe for progress value animation. Since we will animate the width of the pseudo-element, the value will represent the progress percentage:
@keyframes progress-animation to width: 75%; > >
Then we need to set the pseudo-element width to 0 and then specify the animation property.
.progress-container::before content: ""; position: absolute; top: 0; left: 0; height: 100%; background: turquoise; width: 0; animation: progress-animation .7s ease-in forwards; >
Finally to complete the animation we need to animate the percentage value stored in the pseudo-element. There’s a way to animate the numeric value using the CSS counter.
NOTE: Animating numeric values using CSS is not supported by all browsers! So as a workaround you can set pseudo-elements’ content value to a progress value (e.g. “75%”) without animation.
@property --num syntax: ''; initial-value: 0; inherits: false; > .progress-label::after counter-reset: num var(--num); content: counter(num) '%'; position: absolute; top:0; right: 0; animation: progress-text 1s ease-in forwards; > @keyframes progress-text to --num: 75; > >
Demo
The end result can be viewed on CodePen:
Кастомизация HTML5 progress element
Прогрессбар — элемент вроде и редко встречающийся на сайтах (в отличии от селектов, чекбоксов, инпутов и прочего), но все равно без него не обойдется ни один ui-kit.
На данный момент HTML5 предоставляет нам нативный элемент progress, базовый функционал которого поддерживается практически всеми современными браузерами (caniuse.com/#feat=progress).
Но на базовых возможностях стилизации представляемых скажем IE11, мягко говоря далеко не уедешь. Все же хочется чтобы прогрессбары были с анимацией, градиентом, плавной сменой ползунка прогресса, и самое главное с выводом значения в процентах.
В этой статье я попытаюсь показать способ кастомизации прогрессбара, исходя из двух условий:
- Никакого JS. Вся стилизация делается исключительно средствами CSS;
- При последующей работе с кастомизированным прогрессбаром, мы должны работать исключительно с ним (менять значение и не думать о том что нужно поменять ширину ползунка или подставить правильный процент).
document.getElementById('progress').value = '50';
Сразу скажу что при верстке я всегда стараюсь использовать средства CSS по максимуму, на столько на сколько это возможно не прибегая к помощи JS. Так что такой способ может показаться кому-то излишним. Так же в примере будет использован препроцессор, так как без него очень долго писать нужные стили. Я предпочитаю LESS, но при написании статьи я так и не нашел ни одной вменяемой песочницы с поддержкой LESS. Так что в примере будет SCSS.
Итак, начнем с базовой HTML разметки:
.progress < font: 12px Arial, Tahoma, sans-serif; position: relative; overflow: hidden; >.progress progress < position: absolute; width: 0; height: 0; overflow: hidden; left: -777px; >.progress-bar < overflow: hidden; background: #ac92ec; width: 0; height: 100%; position: absolute; top: 0; left: 0; >.progress-value < color: #333; display: block; line-height: 21px; text-align: center; >.progress-bg
@keyframes progress_bar < 0% < background-position: 0 0; >100% < background-position: -40px 0; >> .progress-bar < transition: width 1s linear; >.progress-bar:after
И самый главный момент, — это проставление width для прогресса, и числового значения в процентах. Тут все просто, логика будет следующая:
.progress progress[value="1"] + .progress-value:before < content: "1%"; >.progress progress[value="1"] ~ .progress-bg .progress-bar
Как не сложно догадаться, таких правил нам нужно ровно 100, для этого нам и нужны препроцессоры:
@for $i from 0 through 100 < .progress progress[value="#"] < & + .progress-value:before < content : '#%' > & ~ .progress-bg .progress-bar < width: $i * 1% >> >
.generate-progress(@n, @i: 0) when (@i =< @n) < .progress progress[value="@"] < & + .progress-value:before < content : '@%' > & ~ .progress-bg .progress-bar < width: @i * 1% >> .generate-progress(@n, (@i + 1)); > .generate-progress(100);
Безусловно здесь есть большой минус — много CSS на выходе. Но по мне плюсы этого метода перекрывают огромный CSS код.