- background-color¶
- Демо¶
- Синтаксис¶
- Значения¶
- background-color
- Интерактивный пример
- Синтаксис
- Значения
- Формальный синтаксис
- Примеры
- HTML
- CSS
- Результат
- Проблемы доступности
- Спецификации
- Совместимость с браузерами
- Смотрите также
- Found a content problem with this page?
- HTML Background Color Tutorial – How to Change a Div Background Color, Explained with Code Examples
- Default Background Color of an Element
- Changing the Background Color of a Div
- Background Color and the CSS Box Model
- Background-color Values
- Extra Note
- Conclusion
- CSS background-color Property
- Browser Support
- CSS Syntax
- Property Values
- More Examples
- Example
- Example
- Example
- Example
- Example
- Example
background-color¶
Свойство background-color определяет цвет фона элемента.
Хотя это свойство не наследует свойства своего родителя, из-за того, что начальное значение устанавливается прозрачным, цвет фона дочерних элементов совпадает с цветом фона родительского элемента.
Демо¶
- background
- background-attachment
- background-blend-mode
- background-clip
- background-color
- background-image
- background-origin
- background-position
- background-position-x
- background-position-y
- background-repeat
- background-size
Синтаксис¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
/* Keyword values */ background-color: red; /* Hexadecimal value */ background-color: #bbff00; /* Hexadecimal value with alpha channel */ background-color: #11ffee00; /* 00 - fully transparent */ background-color: #11ffeeff; /* ff - fully opaque */ /* RGB value */ background-color: rgb(255, 255, 128); /* RGBA value or RGB with alpha channel */ background-color: rgba( 117, 190, 218, 0 ); /* 0.0 - fully transparent */ background-color: rgba( 117, 190, 218, 0.5 ); /* 0.5 - semi-transparent */ background-color: rgba( 117, 190, 218, 1 ); /* 1.0 - fully opaque */ /* HSLA value */ background-color: hsla(50, 33%, 25%, 0.75); /* Special keyword values */ background-color: currentcolor; background-color: transparent; /* Global values */ background-color: inherit; background-color: initial; background-color: unset;
Значения¶
background-color: transparent;
Применяется ко всем элементам
background-color
CSS-свойство background-color CSS устанавливает цвет фона элемента.
Интерактивный пример
Синтаксис
/* Словесные значения */ background-color: red; /* Шестнадцатеричное значение */ background-color: #bbff00; /* Шестнадцатеричное значение с alpha-каналом */ background-color: #11ffee00; /* 00 - полностью прозрачный */ background-color: #11ffeeff; /* ff - непрозрачный */ /* RGB-значение */ background-color: rgb(255, 255, 128); /* RGBA-значение или RGB с alpha-каналом */ background-color: rgba(117, 190, 218, 0.0); /* 0.0 - полностью прозрачный */ background-color: rgba(117, 190, 218, 0.5); /* 0.5 - полупрозрачный */ background-color: rgba(117, 190, 218, 1.0); /* 1.0 - непрозрачный */ /* HSLA-значение */ background-color: hsla(50, 33%, 25%, 0.75); /* Специальные словесные значения */ background-color: currentColor; background-color: transparent; /* Общие значения */ background-color: inherit; background-color: initial; background-color: unset;
Свойство background-color определяется единственным значением .
Значения
Формальный синтаксис
Примеры
HTML
div class="exampleone"> Lorem ipsum dolor sit amet, consectetuer div> div class="exampletwo"> Lorem ipsum dolor sit amet, consectetuer div> div class="examplethree"> Lorem ipsum dolor sit amet, consectetuer div>
CSS
.exampleone background-color: teal; color: white; > .exampletwo background-color: rgb(153, 102, 153); color: rgb(255, 255, 204); > .examplethree background-color: #777799; color: #FFFFFF; >
Результат
Проблемы доступности
Важно обеспечить достаточный цветовой контраст между цветом текста и фоном, чтобы люди со слабым зрением могли его прочитать, но при этом должна быть достаточная разница между введённым текстом и текстом placeholder, чтобы пользователь не путал их.
Коэффициент цветового контраста определяется путём сравнения яркости текста placeholder и цветом фона формы ввода. Чтобы соответствовать рекомендациям Web Content Accessibility Guidelines (WCAG), требуется соотношение 4.5:1 для основного текста и 3:1 для более крупного текста, например, заголовков. Крупный текст определяется как 18.66px и больше с жирным начертанием или 24px и больше с обычным начертанием.
Спецификации
Совместимость с браузерами
BCD tables only load in the browser
Смотрите также
Found a content problem with this page?
This page was last modified on 10 окт. 2022 г. by MDN contributors.
Your blueprint for a better internet.
HTML Background Color Tutorial – How to Change a Div Background Color, Explained with Code Examples
One of the most common things you may have to do as a web developer is to change the background-color of an HTML element. But it may be confusing to do if you do not understand how to use the CSS background-color property.
In the article, we discuss
- the default background color value of an HTML element
- how to change the background color of a div, which is a very common element
- which parts of the CSS box model are affected by the background-color property, and
- the different values this property can take.
Default Background Color of an Element
The default background color of a div is transparent . So if you do not specify the background-color of a div, it will display that of its parent element.
Changing the Background Color of a Div
In this example, we will change the background colors of the following divs.
I love HTML I love CSS I love JavaScript
Without any styling, this will translate to the following visually.
Let’s change the background color of the divs by adding styles to the classes. You can follow along by trying the examples in an HTML file.
.div-1 < background-color: #EBEBEB; >.div-2 < background-color: #ABBAEA; >.div-3 I love HTML I love CSS I love JavaScript
This will result in the following:
Cool! We have successfully changed the background color of this div. Next, let’s get to know more about this property. Let’s see how the background-color property affects parts of the CSS-box model.
Background Color and the CSS Box Model
According to the CSS box model, all HTML elements can be modeled as rectangular boxes. Every box is composed of 4 parts as shown in the diagram below.
You can read up on the box model if you are not familiar with it. The question is, which part of the box model is affected when you change the background color of a div? The simple answer is the padding area and the content area. Let’s confirm this by using an example.
body < background-color: #ABBAEA; >.child This is the parent div which contains the div we are testing
This example shows that changing the background color of a div does not affect the border and margin of the div.
From the example above, we can see that the margin area and the border area are not affected by the change in background color. We can change the color of the border using the border-color property. The margin area remains transparent and reflects the background color of the parent container.
Finally, let’s discuss the values the background-color property can take.
Background-color Values
Just like the color property, the background-color property can take six different values. Let’s consider the three most common values with an example. In the example, we set the background-color of the div to red with different values.
/* Keyword value/name of color */ .div-1 < background-color: red; >/* Hexadecimal value */ .div-2 < background-color: #FF0000; >/* RGB value */ .div-3 The background property can take six different values.
The background property can take six different values.
The background property can take six different values.
Notice that they all result with the same background color.
Other values the background-color property can take include HSL value, special keyword values and global values. Here are examples of each of them.
/* HSL value */ background-color: hsl(0, 100%, 25%; /* Special keyword values */ background-color: currentcolor; background-color: transparent; /* Global values */ background-color: inherit; background-color: initial; background-color: unset;
You can read more on each of these values here.
Extra Note
When setting the background color of an element, it is important to ensure that the contrast ratio of the background color and the color of the text it contains is high enough. This is to ensure that people with low vision can easily read the text.
The contrast between the background color of the first div and the color of the text is not high enough for everyone to see. So unless you are the only one using the website you are building and you have very good eyesight, you should avoid such color combinations.
The second div has a much better contrast ratio between the background color and the color of the text . Thus, it is more accessible and clearer for people to read.
Conclusion
In this article, we saw how you can change the background-color of a div. We also discussed which parts of the CSS box model are affected by the change in background-color. Finally, we discussed the values the background-color property can take.
I hope you found this article useful. Thanks for reading.
CSS background-color Property
The background-color property sets the background color of an element.
The background of an element is the total size of the element, including padding and border (but not the margin).
Tip: Use a background color and a text color that makes the text easy to read.
Default value: | transparent |
---|---|
Inherited: | no |
Animatable: | yes. Read about animatable Try it |
Version: | CSS1 |
JavaScript syntax: | object.style.backgroundColor=»#00FF00″ Try it |
Browser Support
The numbers in the table specify the first browser version that fully supports the property.
CSS Syntax
Property Values
Value | Description | Demo |
---|---|---|
color | Specifies the background color. Look at CSS Color Values for a complete list of possible color values. | Demo ❯ |
transparent | Specifies that the background color should be transparent. This is default | Demo ❯ |
initial | Sets this property to its default value. Read about initial | |
inherit | Inherits this property from its parent element. Read about inherit |
More Examples
Example
Specify the background color with a HEX value:
Example
Specify the background color with an RGB value:
Example
Specify the background color with an RGBA value:
Example
Specify the background color with a HSL value:
Example
Specify the background color with a HSLA value:
Example
Set background colors for different elements:
body <
background-color: #fefbd8;
>
h1 background-color: #80ced6;
>
div background-color: #d5f4e6;
>
span background-color: #f18973;
>