Css hide background color

background — color

Свойство, раскрашивающее фон элемента в яркие краски!

Время чтения: меньше 5 мин

Обновлено 20 декабря 2021

Кратко

Скопировать ссылку «Кратко» Скопировано

При помощи свойства background — color можно задать цвет фона элемента. Задать фоновый цвет можно любому элементу — строчному (inline), блочному (block) или строчно-блочному (inline-block).

Пример

Скопировать ссылку «Пример» Скопировано

   

Розовый — цвет, образующийся.

Жёлтый — самый лёгкий и яркий цвет.
Зелёный цвет.
div class="parent"> p class="block">Розовый — цвет, образующийся. p> span class="inline">Жёлтый — самый лёгкий и яркий цвет. span> div class="inline-block">Зелёный цвет. div> div>
 .block  background-color: pink;> .inline  background-color: rgb(255 216 41);> .inline-block  background-color: #49a16c;> .block  background-color: pink; > .inline  background-color: rgb(255 216 41); > .inline-block  background-color: #49a16c; >      

В примере выше показаны блоки всех трёх типов отображения. С фоном для блочных и строчно-блочных элементов проблем не возникает, а вот со строчными элементами всё не так просто.

Если высота строки ( line — height ) у строчного элемента будет больше 1, то между строками будут пробелы.

Но в заливке фона строчных элементов есть и преимущества! На последней строке фон заканчивается ровно там, где заканчивается текст.

Помимо этой особенности, в CSS-коде видно, что в качестве значения для background — color можно использовать любое доступное обозначение цвета в вебе.

Как понять

Скопировать ссылку «Как понять» Скопировано

Свойство background — color меняет цвет фона любого элемента.

Как пишется

Скопировать ссылку «Как пишется» Скопировано

Для нужного селектора указываем свойства background — color и после двоеточия указываем цвет фона в любом доступном для веба формате.

 .element  background-color: black;> .element  background-color: black; >      
 .element  background-color: #ffffff;> .element  background-color: #ffffff; >      
 .element  background-color: #ffffff80;> .element  background-color: #ffffff80; >      
 .element  background-color: rgb(255 255 0 / 0.5);> .element  background-color: rgb(255 255 0 / 0.5); >      

Помимо цвета можно задать прозрачный фон при помощи ключевого слова transparent .

Это бывает полезно для изменения цвета при наведении курсора.

Подсказки

Скопировать ссылку «Подсказки» Скопировано

💡 Свойство фона не наследуется.

💡 Значение по умолчанию — прозрачный фон: transparent .

💡 Фон нельзя задать частично. Блок заливается указанным цветом полностью.

💡 В качестве значения можно указать только один цвет.

💡 Изменение цвета фона можно анимировать при помощи свойства transition 🥳

На практике

Скопировать ссылку «На практике» Скопировано

Алёна Батицкая советует

Скопировать ссылку «Алёна Батицкая советует» Скопировано

🛠 Если нужна красивая кнопка ( ), то не забудьте сбросить фон: укажите для неё background — color : transparent . Или тот цвет фона, который нужен по дизайну. По умолчанию у всех кнопок серый фон с приветом из девяностых.

🛠 Аналогичным способом можно сделать красивые прозрачные поля ввода ( input ) в формах.

    Email:   form class="form"> label> Email: input class="input" type="text" placeholder="Введите ваш email"> label> button class="submit">Подписатьсяbutton> form>      
 .form  /* Фон для всей формы */ background-color: #ffd829;> .input  /* Прозрачное поле ввода */ background-color: transparent;> .submit  /* Чёрный фон для кнопки */ background-color: black; /* Анимируем всё анимируемое */ transition: 0.3s ease-in-out;> .submit:hover  /* Прозрачный фон при наведении курсора */ background-color: transparent;> .form  /* Фон для всей формы */ background-color: #ffd829; > .input  /* Прозрачное поле ввода */ background-color: transparent; > .submit  /* Чёрный фон для кнопки */ background-color: black; /* Анимируем всё анимируемое */ transition: 0.3s ease-in-out; > .submit:hover  /* Прозрачный фон при наведении курсора */ background-color: transparent; >      

🛠 Если вам нужен градиент, то background — color вам не подойдёт. Градиенты можно задать только при помощи background — image .

🛠 Если нужен блок с «рваным» краем, но без пробела между строками, то для этого есть множество трюков. Один из них:

   Чем отличается маркер от текстовыделителя?  Текстовыделительные маркеры заправляются флуоресцентными полупрозрачными чернилами. Они не покрывают поверхность бумаги плотным слоем, не пропускающим свет, как это делают обычные маркеры на водной или спиртовой основе.   div class="parent"> Чем отличается маркер от текстовыделителя? span class="bkg"> Текстовыделительные маркеры заправляются флуоресцентными полупрозрачными чернилами. Они не покрывают поверхность бумаги плотным слоем, не пропускающим свет, как это делают обычные маркеры на водной или спиртовой основе. span> div>      
 .parent  padding: 25px;> .bkg  font-size: 16px; line-height: 1.5; background-color: #ffd829; /* Тень для каждой строки, перекрывающая пробел */ box-shadow: 0 6px 0 #ffd829;> .parent  padding: 25px; > .bkg  font-size: 16px; line-height: 1.5; background-color: #ffd829; /* Тень для каждой строки, перекрывающая пробел */ box-shadow: 0 6px 0 #ffd829; >      

🛠 С помощью полупрозрачного фонового цвета у псевдоэлемента можно создать красивый оверлей поверх фотографий или фоновых изображений. Это круто, потому что фоном можно будет ставить любую фотографию, и она в большинстве случаев не будет выбиваться из дизайна.

   

The best site all over the world!

header class="header"> h1 class="title">The best site all over the world!h1> header>
 .header  /* Чтобы псевдоэлемент считал своё положение от этого блока */ position: relative; z-index: 0; /* Фоновое изображение на всю ширину и высоту блока */ background: url("background.png") no-repeat center / cover;> .header:before  content: ""; position: absolute; z-index: -1; display: block; top: 0; left: 0; width: 100%; height: 100%; /* Оверлей поверх картинки с прозрачностью 50% */ background-color: rgba(0, 79, 130, 0.5);> .header  /* Чтобы псевдоэлемент считал своё положение от этого блока */ position: relative; z-index: 0; /* Фоновое изображение на всю ширину и высоту блока */ background: url("background.png") no-repeat center / cover; > .header:before  content: ""; position: absolute; z-index: -1; display: block; top: 0; left: 0; width: 100%; height: 100%; /* Оверлей поверх картинки с прозрачностью 50% */ background-color: rgba(0, 79, 130, 0.5); >      

Для .header можно задать любую картинку фоном, и поверх неё всегда будет голубой оверлей 💁‍♀️

Источник

background-color

The background-color CSS property sets the background color of an element.

Try it

Syntax

/* Keyword values */ background-color: red; background-color: indigo; /* Hexadecimal value */ background-color: #bbff00; /* Fully opaque */ background-color: #bf0; /* Fully opaque shorthand */ background-color: #11ffee00; /* Fully transparent */ background-color: #1fe0; /* Fully transparent shorthand */ background-color: #11ffeeff; /* Fully opaque */ background-color: #1fef; /* Fully opaque shorthand */ /* RGB value */ background-color: rgb(255 255 128); /* Fully opaque */ background-color: rgb(117 190 218 / 0.5); /* 50% transparent */ /* HSL value */ background-color: hsl(50 33% 25%); /* Fully opaque */ background-color: hsl(50 33% 25% / 0.75); /* 75% opaque, i.e. 25% transparent */ /* Special keyword values */ background-color: currentcolor; background-color: transparent; /* Global values */ background-color: inherit; background-color: initial; background-color: revert; background-color: revert-layer; background-color: unset; 

The background-color property is specified as a single value.

Values

The uniform color of the background. It is rendered behind any background-image that is specified, although the color will still be visible through any transparency in the image.

Accessibility concerns

It is important to ensure that the contrast ratio between the background color and the color of the text placed over it is high enough that people experiencing low vision conditions will be able to read the content of the page.

Color contrast ratio is determined by comparing the luminance of the text and background color values. In order to meet current Web Content Accessibility Guidelines (WCAG), a ratio of 4.5:1 is required for text content and 3:1 for larger text such as headings. Large text is defined as 18.66px and bold or larger, or 24px or larger.

Formal definition

Formal syntax

Examples

HTML

div class="exampleone">Lorem ipsum dolor sit amet, consectetuerdiv> div class="exampletwo">Lorem ipsum dolor sit amet, consectetuerdiv> div class="examplethree">Lorem ipsum dolor sit amet, consectetuerdiv> 

CSS

.exampleone  background-color: transparent; > .exampletwo  background-color: rgb(153, 102, 153); color: rgb(255, 255, 204); > .examplethree  background-color: #777799; color: #ffffff; > 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 18, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

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

Источник

Читайте также:  Python форматирование строки float
Оцените статью