background-color

The Friendly Guide to CSS Background Color

Designing an HTML page using CSS allows for an amazing array of options and ideas to bring out your creative output. Applying that creativity through the use of a CSS Background Color is one of the more impactful elements in the CSS toolkit. It stands as a definite cornerstone of design within CSS.

Quite directly, the CSS Background Color property was created to allow the designer to implement values to the background of an HTML page. This can range from simple colored background and images to more advanced ideas such as double gradients and multiple layered images. In this brief tutorial, the concepts of the CSS Background Color property will be covered to provide a stable starting point for CSS beginners just getting started.

Syntax of the CSS Background Property

Setting a CSS background color is a rather straightforward concept. To achieve this, you will need to call upon the background property of your chosen selector. In the code example below you will see a sample setup for this as it changes the body background color.

Note: Do not forget to add the dash in between “background” and “color” as shown below. The browser cannot interpret the CSS property if it is not set as “background-color.”

 body   background-color: blue; >

The HTML body tag is the selector used in this example. Within that selector, we call the intended property to change the background color. You can see that the background-color property has been used with the value assigned set to the color blue. This provides the following output on the HTML page as shown below.

In that example, you can notice the black text is a bit difficult to read against the rather heavy blue background. The text sits within a div element on the HTML code for the page. For another example, this can also be manipulated with the background-color property as well. See the code example below.

 body  background-color: blue; > div  background-color: white; >

Here, the div selector was used with the background-color property called. The value of the div’s background color was set to white. Once saved and reloaded, the HTML file produces the following result in the browser window.

You can now see the div element now has a white background applied to it allowing the text to be easier to read.

Setting CSS Background Color with Hex Codes

Using basic color definitions can be easy to apply, although it can also be limiting in more creative needs. For these instances, the use of hexadecimal color codes can be applied. Known as “hex codes” for shorthand reference, these codes allow a CSS designer to select the exact color shade that fits with the desired need of the page design. Take a look at the sample code provided below.

 body  background-color: #ff0000; > div  background-color: white; > 

Here, the CSS background color for the body element has been changed from blue to the hex code of “#ff0000.” This is the hex code for the color red which provides the following output on the page.

However, if this shade of red is not what fits with the design, it can be modified, or rather refined, with a hex code. The code example below shows a new hex code used to apply a lighter rose tone to the background.

 body  background-color: #B97777; > div  background-color: white; >

This new hex code of “#B97777” will provide the following CSS background color to the HTML page.

Set the Transparency & Opacity for CSS Background Color

Utilizing CSS for background colors can also extend beyond the idea of shades. It can also allow for levels of transparency and opacity to refine the way the background appears on the site. To achieve this, you can use the following properties of “opacity” and “RGBA.” To begin, here is an example of the opacity property being used.

 body  background-color: #C100AD; opacity: 1.0; > div  background-color: white; >

This provides the following background effect.

The background color as shown in the image above is quite opaque. This can be changed by altering the value of the opacity property. The acceptable range for this is “0.0” to “1.0.” The higher the value, the higher the opacity. Respectively, a lower value results in a more transparent color. See the example below where the opacity value has been reduced to “0.2.”

 body  background-color: #C100AD; opacity: 0.2; > div  background-color: white; >

This will output the following level of opacity on the background color for the page.

The opacity of the color has indeed been reduced, however, it is also apparent that the div element has also had its own white background reduced in opacity as well. This leaves the text within the div difficult to read for most users. This is due to the fact that all the child elements of the HTML tag used will then inherit the same value for the opacity property.

To handle this, the “RGBA” property can be used in place of the opacity property. The acronym of RGBA stands for the values of red, green, blue, and alpha. While the color values represent the actual colors, the alpha value represents the value of the opacity. It still runs on the same range of “0.0” to “1.0.”

In this code example below, the value of the background color has been set using the “background” property and the RGBA values applied.

Note: The “background-color” property is NOT used here.

 body  background: rgba(240, 0, 168, 0.37) > div  background-color: white; >

This will provide the following change to the background.

Here, the background coloration and opacity have been applied to the site without changing the values for the div’s own background setting. In this method, you can work with a parent element without forcing the values down onto the child elements.

Note: You are not expected to simply know all hex codes and RBGA values from the top of your head at all times. These can be found on multiple online resources to assist you in setting the perfect colors. Do not stress on this aspect.

Building on the Basics

Being able to work with the CSS background color property is a powerful way to make a site stand out for both artistic and navigation design purposes. However, that is just the proverbial tip of the iceberg for what is possible using CSS. Other strong tools in the belt include setting background images as well as relative background-attachment settings to the site. Having access to these options and more can quickly provide you with a very competent springboard to greater design abilities. With the door open for more control, you also set the path for creativity to flow.

The modern world runs on code and that code comes from people like you. If you are looking to fly farther and stronger than ever before, take the first steps with code. Learning to code can help you open doors to those new possibilities of a better you. Embrace Udacity’s Intro to Programming Nano degree today to start the journey.

Источник

background-color

Определяет цвет фона элемента. Хотя это свойство не наследует свойства своего родителя, из-за того, что начальное значение устанавливается прозрачным, цвет фона дочерних элементов совпадает с цветом фона родительского элемента.

Синтаксис

background-color: | transparent | inherit

Значения

transparent Устанавливает прозрачный фон. inherit Наследует значение родителя.

HTML5 CSS2.1 IE Cr Op Sa Fx

       

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat.

В данном примере для элементов веб-страницы применяется три различных способа задания фонового цвета. Результат примера показан на рис. 1.

Применение background-color

Рис. 1. Применение background-color

Объектная модель

[window.]document.getElementById(» elementID «).style.backgroundColor

Браузеры

Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .

Источник

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;
>

Источник

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.

Источник

Читайте также:  Php get called file
Оцените статью