CSS background — скорочення для всіх фонових властивостей
Властивість background задає колір тла, або його зображення.
Це універсальна властивість для всіх background властивостей, котра в собі дозволяє задавати значення декількох CSS-властивостей, а саме:
background-color
background-image
background-position
background-size
background-repeat
background-origin
background-clip
background-attachment
Працюють будь-які комбінації значень, всі комбінації розділяються між собою прогалиною. Значення можуть йти в довільному порядку, браузер сам визначить, яке з них за що відповідає. Пропущені властивості отримують значення без задання (initial). Жодне значення не є обов'язковим, тому значення, що не використовуються можна не вказувати.
Використовуючи одночасно background-position й background-size потрібно розділити їх за допомогою символу слеш - / .
Використовуй цю властивість, щоб пришвидшити завантаження сторінки, адже такий код
background: url(sweettexture.jpg) top center / 200px 200px no-repeat fixed padding-box content-box red;
Буде завантажуватися швидше, ніж ось такий
background: url(sweettexture.jpg);
background-position: top center;
background-size: 200px 200px;
background-repeat: no-repeat;
background-attachment: fixed;
background-origin: padding-box;
background-clip: content-box;
background-color: red;
Єдиний недолік - це читабельність, адже перший варіант хоч і коротший, але складніший для сприйняття, але ніщо тобі не заважає використовувати коментарі.
background:
url(sweettexture.jpg) /* image */
top center / 200px 200px /* position / size */
no-repeat /* repeat */
fixed /* attachment */
padding-box /* origin */
content-box /* clip */
red; /* color */
В CSS3 з'явилася підтримка багатошарового тла, де кожен шар знаходяться один над одним (як в фоторедакторі). Відповідно будь-яка властивість, пов'язана з тлом, може приймати список значень, розділений комами, наприклад:
body {
background: url(tlo1.jpg), url(tlo2.jpg) black;
background-repeat: repeat-x, no-repeat;
}
Кожне значення з переліку відповідає шару:
перше значенням - це перший (верхній) шар;
друге значення - другий (середній) шар;
третє значення - останній (найнижчий) шар. В нашому випадку це колір тла;
Загальний опис
автор: NagarD
- Порада
-
Якщо використовувати
автор: NagarDbackground-imageразом зbackground-color, то у випадку помилки, наприклад, не завантажилася картинка, для тла застосується значення кольору. Єдина умова такої роботи -background-imageмає перебувати післяbackground-color. - Порада
-
Властивість
автор: NagarDbackgroundможна використовувати як зображення замість тегу<img>
Синтаксис
background: bg-color bg-image bg-position/bg-size bg-repeat bg-origin bg-clip bg-attachment initial|inherit|unset;
Властивість background може отримувати 11 значень:
-
background-image -
Задає одине, або кілька зображень як тло.
автор: NagarD -
background-color -
Задає колір тла
автор: NagarD -
background-position -
Вказує положення зображення, що буде тлом
автор: NagarD -
background-size -
Вказує розмір фонових зображень
автор: NagarD -
background-repeat -
Визначає, як повторювати фонові зображення
автор: NagarD -
background-origin -
Визначає область позиціонування фонових зображень
автор: NagarD -
background-clip -
Визначає, як колір тла або фонова картинка повинна виводитися під границями
автор: NagarD -
background-attachment -
Вказує, чи повинно фіксуватися або прокручуватися фонове зображення з іншою частиною сторінки
автор: NagarD -
initial -
Встановлює властивість у значення без задання
автор: NagarD -
inherit -
Вказує на спадковість властивості від свого батьківського елемента.
автор: NagarD -
unset -
Працює як inherit, але якщо значення не задане - властивості буде задано значення -
initial
автор: NagarD
| Значення без задання: | transparent || none || repeat || scroll || 0% 0% |
|---|---|
| Наслідує: | Ні |
| Анімується: | Так |
| JavaScript синтаксис: | object.style.background="red url(smiley.gif) top left no-repeat" |
Переглядачі
| Переглядач | ||||||
|---|---|---|---|---|---|---|
| 1 | 1 | 1 | 3.5 | 12 | 4 | |
| одне тло | 1.0 | 1.0 | 1.0 | 3.5 | 4.0 | |
| декілька фонів | 1.0 | 3.6 | 1.3 | 10.5 | 9.0 |
| Переглядач | ||||
|---|---|---|---|---|
| 2 | 18 | 4 | 1 | |
| одне тло | 2.1 | 1.0 | 3.2 | |
| декілька фонів | 2.1 | 1.0 | 3.2 |
Приклади
+ запропонувати свій приклад у пісочниці
Інструменти
Перекладає колір між HEX, RGB і HSL — кожне поле і вхід, і вихід.
Конвертер кольорів — окремою сторінкою, з поясненням пасток.
Складає лінійний або радіальний градієнт і віддає готовий background.
Генератор градієнта — окремою сторінкою, з поясненням пасток.
Кілька властивостей background-* однією декларацією: колір тла, зображення, заборона повторення, прикріплення і позиція по центру.
HTML
<div class="banner">
<p>Колір + картинка + no-repeat + fixed + center — одним рядком.</p>
</div>
CSS
.banner {
height: 160px;
background: #00ff00 url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 40 40' width='40'%3E%3Ccircle cx='20' cy='20' r='18' fill='gold'/%3E%3Ccircle cx='14' cy='15' r='3'/%3E%3Ccircle cx='26' cy='15' r='3'/%3E%3Cpath d='M12 26q8 6 16 0' stroke='black' stroke-width='2' fill='none'/%3E%3C/svg%3E") no-repeat fixed center;
}
Два однакові блоки; другому дописано background: #ffd9d0 — коротка форма стерла і картинку, і її розмір.
HTML
<div class="box a">Налаштовано окремими властивостями</div>
<div class="box b">Знизу дописано background: #ffd9d0</div>
CSS
body {
font-family: sans-serif;
font-size: 15px;
padding: 20px;
}
.box {
padding: 24px;
margin-bottom: 14px;
border: 1px solid #cfd4d9;
background-image: linear-gradient(45deg, #b6e3f4 25%, transparent 25%,
transparent 75%, #b6e3f4 75%);
background-size: 26px 26px;
}
.b {
background: #ffd9d0;
}
Динамічна зміна тла сторінки
HTML
<p>Натисни на екран, щоб змінити фон.</p>
CSS
* {
padding: 0;
margin: 0;
}
body {
height: 100vh;
display: grid;
user-select: none;
align-items: center;
justify-content: center;
}
p {
font-size: 24px;
font-family: monospace;
line-height: 1;
font-weight: 700;
text-shadow: 1px 1px 0px #4f4f4f;
}
JS
window.onclick = function () {
randomColor = '#' + (Math.random() * 0xFFFFFF << 0).toString(16);
document.body.style.background = randomColor;
};
//# sourceURL=pen.js
HTML
<div class="container">
<header>
<h1>Тло для заголовку</h1>
</header>
<main>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur.</p>
</main>
</div>
CSS
.container {
width: 450px;
line-height: 1.5;
font-family: sans-serif;
}
header {
color: #fff;
padding: 12px;
background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='200' viewBox='0 0 40 40' preserveAspectRatio='none'%3E%3Crect width='40' height='40' fill='%23264653'/%3E%3Cpath d='M0 40 12 18 22 30 30 22 40 40Z' fill='%232a9d8f'/%3E%3Ccircle cx='30' cy='9' r='5' fill='%23e9c46a'/%3E%3C/svg%3E") /* background-image */
#000; /* background-color */
}
HTML
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
CSS
div {
background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16'%3E%3Cpath d='M2 2 14 8 2 14Z' fill='%23e76f51'/%3E%3C/svg%3E") no-repeat fixed 10px 100px;
}
p {
width: 400px;
font-family: sans-serif;
font-size: 17px;
line-height: 1.45;
padding-left: 35px;
}
HTML
<h4>Властивість <code>background</code></h4>
<div class="demo">
<div class="block hex">колір</div>
<div class="block image">зображення</div>
<div class="block gradient">градієнт</div>
</div>
CSS
* {
box-sizing: border-box;
}
body {
font-family: sans-serif;
line-height: 1.45;
font-size: 18px;
padding: 16px 16px 0 16px;
text-align: center;
}
h4 {
color: #4f4f4f;
font-weight: 400;
}
.demo {
display: flex;
align-items: center;
justify-content: space-between;
}
.block {
background: #000;
width: 150px;
height: 150px;
border: 8px solid #4f4f4f;
font-family: monospace;
line-height: 150px;
font-size: .8em;
color: #fff;
}
.hex { background: #32321A; }
.image { background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='150' height='150' viewBox='0 0 40 40' preserveAspectRatio='none'%3E%3Crect width='40' height='40' fill='%23264653'/%3E%3Cpath d='M0 40 12 18 22 30 30 22 40 40Z' fill='%232a9d8f'/%3E%3Ccircle cx='30' cy='9' r='5' fill='%23e9c46a'/%3E%3C/svg%3E"); }
.gradient { background: linear-gradient(#4DAB6B, #FFC50F); }
HTML
<h1>Переглянь, що можна творити з тлом</h1>
<p id="debug" class="debug">(клацни на блок)</p>
<ul class="options__first">
<li class="option__flat">
Flat Color
<ul class="options__second hidden">
<li data-type="hex">Hex Code</li>
<li class="option__name" data-type="name">Color Name</li>
<li class="option__opacity" data-type="opacity">Opacity</li>
</ul>
</li>
<li class="option__image">
Image
<ul class="options__second hidden">
<li class="option__image option__positioned" data-type="positioned">Positioned</li>
<li class="option__sprite" data-type="sprite">Sprite</li>
<li class="option__image image__repeating" data-type="repeating">Repeating</li>
<li class="option__image option__multiple" data-type="multiple">Multiple</li>
<li class="image__opacity" data-type="image_opacity">Opacity</li>
</ul>
</li>
<li class="option__gradient">
Gradient
<ul class="options__second hidden">
<li class="option__gradient" data-type="linear">Linear</li>
<li class="option__radial" data-type="radial">Radial</li>
<li class="option__striped" data-type="striped">Striped</li>
<li class="option__repeating" data-type="repeating">Repeating</li>
</ul>
</li>
</ul>
<pre class="hide"><code id="code">
some-code: here;
</code></pre>
CSS
body {
font-family: Avenir Next;
text-align: center;
min-width: 300px;
}
ul {
position: relative;
list-style: none;
margin: 0;
padding: 0;
transition: transform 200ms linear;
display: flex;
justify-content: center;
max-width: 800px;
min-width: 300px;
margin: 0 auto;
}
ul.left-selected {
transform: translateX(19.8%);
}
ul.right-selected {
transform: translateX(-19.8%);
}
.options__first {
font-size: 1.1em;
}
.options__first li {
color: white;
height: 125px;
width: 125px;
margin: 8px 16px;
background: #0081B6;
cursor: pointer;
line-height: 125px;
}
.options__first .option__image {
background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='800' height='600' viewBox='0 0 40 40' preserveAspectRatio='none'%3E%3Crect width='40' height='40' fill='%23264653'/%3E%3Cpath d='M0 40 12 18 22 30 30 22 40 40Z' fill='%232a9d8f'/%3E%3Ccircle cx='30' cy='9' r='5' fill='%23e9c46a'/%3E%3C/svg%3E");
background-size: cover;
}
.options__first .option__gradient {
background-image: linear-gradient(#002e4b, #0081b6);
}
.options__first .option__radial {
background-image: radial-gradient(80% 40%, #002e4b, #0081b6);
}
.options__first .option__striped {
background: linear-gradient(#002e4b 55%, #0081b6 55%);
}
.options__first .option__positioned {
background-position: top right;
}
.options__first .option__repeating {
background: linear-gradient(#002e4b 50%, #0081b6 50%);
background-size: 100% 50px;
background-position: 0 35px;
}
.options__first .option__sprite {
background: none;
color: #0081B6;
line-height: 110px;
}
.options__first .option__sprite:after {
content: '';
height: 50px;
width: 50px;
background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='800' height='600' viewBox='0 0 40 40' preserveAspectRatio='none'%3E%3Crect width='40' height='40' fill='%23264653'/%3E%3Cpath d='M0 40 12 18 22 30 30 22 40 40Z' fill='%232a9d8f'/%3E%3Ccircle cx='30' cy='9' r='5' fill='%23e9c46a'/%3E%3C/svg%3E");
background-size: 200px auto;
background-position: 30% 40%;
display: block;
position: absolute;
bottom: 8px;
left: 27.4%;
z-index: -1;
}
.options__first .image__repeating {
background-size: auto 32%;
}
.options__first .option__multiple {
background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='60' height='60'%3E%3Ccircle cx='15' cy='15' r='6' fill='%23e76f51'/%3E%3C/svg%3E"), url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='800' height='600' viewBox='0 0 40 40' preserveAspectRatio='none'%3E%3Crect width='40' height='40' fill='%23264653'/%3E%3Cpath d='M0 40 12 18 22 30 30 22 40 40Z' fill='%232a9d8f'/%3E%3Ccircle cx='30' cy='9' r='5' fill='%23e9c46a'/%3E%3C/svg%3E");
background-size: 210%, 200%;
background-repeat: no-repeat, no-repeat;
background-position: 145% 0, 0 0;
}
.options__first .image__opacity {
position: relative;
z-index: 1;
background: white;
}
.options__first .image__opacity:after {
content: '';
background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='800' height='600' viewBox='0 0 40 40' preserveAspectRatio='none'%3E%3Crect width='40' height='40' fill='%23264653'/%3E%3Cpath d='M0 40 12 18 22 30 30 22 40 40Z' fill='%232a9d8f'/%3E%3Ccircle cx='30' cy='9' r='5' fill='%23e9c46a'/%3E%3C/svg%3E");
background-size: cover;
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
display: block;
opacity: 0.5;
z-index: -1;
}
.options__first .option__name {
background: rebeccapurple;
}
.options__first .option__opacity {
background: rgba(0, 129, 182, 0.7);
}
.options__second {
display: flex;
margin: 32px 0;
width: 500%;
left: -200%;
max-width: 1000px;
}
.hidden {
display: none;
}
.hide {
opacity: 0;
}
pre {
text-align: left;
background: #333538;
padding: 24px;
border-radius: 4px;
box-shadow: 0 0 2px #111 inset;
margin-top: 200px;
color: white;
font-size: 2em;
overflow-x: auto;
transition: opacity 200ms linear;
}
.debug {
margin-top: -8px;
}
JS
var main_options = document.querySelector('.options__first').children('li');
var $selected_option;
var pre = document.querySelector('#code').parent();
var code_examples = {
hex: '.example {\n background: #333;\n}',
name: '.example {\n background: rebeccapurple;\n}',
opacity: '.example {\n background: rgba(0, 129, 182, 0.7);\n}',
positioned: '.example {\n background: url(...);\n background-position: 100px 0;\n}',
sprite: '.example:after {\n content: "";\n background: url(...);\n height: 100px;\n width: 100px;\n display: block;\n}',
repeating: '.example {\n background: url(...);\n background-repeat: repeat;\n background-size: 50%;\n}',
multiple: '.example {\n background: url(...), url(...);\n background-size: 210%, 200%;\n background-repeat: no-repeat, no-repeat;\n background-position: 145% 0, 0 0;\n}',
image_opacity: '.example:after {\n content: "";\n background: url(...);\n position: absolute;\n top: 0;\n left: 0;\n height: 100%;\n width: 100%;\n display: block;\n opacity: 0.5;\n}',
linear: '.example {\n background: linear-gradient(to top, white, black);\n}',
radial: '.example {\n background: radial-gradient(80% 40%, white, black);\n}',
striped: '.example {\n background: linear-gradient(white 50%, black 50%);\n}',
repeating: '.example {\n background: linear-gradient(white 50%, black 50%);\n background-size: 100% 50px;\n}' };
document.querySelector('[data-type]').click(function () {
var attr = this.getAttribute('data-type');
var html = code_examples[attr];
document.querySelectorAll('#code').forEach((n) => n.innerHTML = html);
pre.removeClass('hide');
return false;
});
main_options.click(function () {
var this = this;
pre.addClass('hide');
if ($selected_option) {
$selected_option.querySelectorAll('.options__second').addClass('hidden');
}
$selected_option = this;
document.querySelector('.options__first').removeClass('left-selected right-selected');
if (main_options.index(this) == 0) {
document.querySelector('.options__first').addClass('left-selected');
}
if (main_options.index(this) == 2) {
document.querySelector('.options__first').addClass('right-selected');
}
this.querySelectorAll('.options__second').removeClass('hidden');
});
Коментарі
Коментарів ще немає — будьте першим!