Серёжа СыроежкинКопирайтер
Фон для сайта HTML можно изменить как с помощью атрибутов тега body, так и с помощью CSS-стилей, примененных также к тегу body. Рассмотрим оба варианта как сделать фон для сайта.
Меняем цвет фона с помощью HTML
Тег body, как и практически любой HTML-тег имеет свои атрибуты. К атрибутам тега body относятся:
- bgcolor — определяет цвет фона для страницы;
- background — позволяет задать картинку в качестве фона веб-страницы (подробно этот вопрос рассмотрен в статье: Как сделать фон сайта картинкой HTML);
- scroll — управляет отображением полосы прокрутки на странице;
- text — задает базовый цвет текста, который будет выводиться на веб-странице;
- bgproperties — указывает, будет ли прокручиваться фон вместе со страницей;
- link — управляет цветом ссылок по умолчанию на странице;
- alink — устанавливает цвет для активной ссылки;
- vlink — определяет цвет для посещенной ссылки на странице;
- leftmargin/rightmargin — задает отступ контента от левого или правого края окна браузера;
- topmargin/bottommargin — задает отступ контента от верхнего или нижнего края окна браузера;
Чтобы изменить цвет фона с помощью HTML, воспользуемся атрибутом bgcolor:
<html>
<head>
<title>Меняем фон сайта с помощью HTML - Нубекс</title>
</head>
<body bgcolor="#fa8e47" text="#fff">
<p>Это пример текста белого цвета, заданного с помощью атрибута text тега body.</p>
</body>
</html>
Примечание: Рекомендуется определять цвет фона страницы, даже если фон белый. Это связано с тем, что некоторые пользователи могут использовать в браузере нестандартный цвет фона, и из-за этого текст на вашем сайте может быть нечитабельным.
Меняем цвет фона страницы с помощью CSS
Во избежании избыточности кода, рекомендуется всё, что связано с оформлением страницы, переносить на плечи CSS. К этому числу относится и задание цвета фона. CSS фон задается следующим образом:
<html>
<head>
<title>Меняем фон сайта с помощью CSS - Нубекс</title>
<style>
body {
background: #fa8e47;
color: #fff;
}
</style>
</head>
<body>
<p>Это пример текста белого цвета, заданного с помощью background CSS. Фон страницы также задан с помощью CSS.</p>
</body>
</html>
В конструкторе сайтов «Нубекс» для любого сайта можно выбрать уже готовый фон из большой билиотеки изображений, или добавить свой.
Смотрите также:
-
1
Определите цвет фона, который вы хотите использовать. В HTML цвета задаются кодами, которые определяют различные оттенки. Воспользуйтесь бесплатным онлайн-инструментом W3Schools HTML Color Picker, чтобы найти коды нужных цветов:
- Перейдите на страницу https://www.w3schools.com/colors/colors_picker.asp в веб-браузере компьютера.
- Выберите базовый цвет, который хотите использовать, в разделе «Pick a Color» (Выбрать цвет).
- Выберите оттенок в правой части страницы.
- Запишите код, который отобразится справа от выбранного оттенка.
-
2
Откройте HTML-файл в текстовом редакторе. Помните, что в HTML5 атрибут <bgcolor> больше не поддерживается. Поэтому цвет фона и другие параметры стиля страницы задаются с помощью CSS.[1]
- HTML-документ можно открыть в Notepad++ или Блокноте (Windows), а также в TextEdit или BBEdit (Mac).
-
3
Добавьте заголовок «html» в документ. Все параметры стиля страницы, включая цвет фона, должны находиться между тегами
<style></style>
:<!DOCTYPE html> <html> <head> <style> </style> </head> </html>
-
4
Создайте пустую строку между тегами «style». На этой строке, которая должна находиться под тегом
<style>
и над тегом</style>
, вы введете необходимую информацию. -
6
Добавьте элемент «body». Введите следующий код между тегами
<style></style>
:- Все, что будет заключено внутри элемента «body» в CSS, повлияет на всю страницу.
- Пропустите этот шаг, если хотите создать градиентный фон.
Реклама
5
-
1
Найдите заголовок «html». Он должен быть в верхней части документа.
-
2
Добавьте свойство «background-color» в элемент «body». Введите
background-color:
в фигурных скобках внутри элемента «body». Должен получиться следующий код:body { background-color: }
- Обратите внимание, что в этом коде необходимо использовать слово «color», а не «colour».
-
3
Добавьте нужный цвет фона в свойство «background-color». Справа от «background-color:» введите числовой код выбранного цвета, а затем введите точку с запятой (;). Например, чтобы фон страницы сделать розовым, напишите следующий код:
body { background-color: #d24dff; }
-
4
Просмотрите информацию внутри тегов «style». На этом этапе заголовок вашего HTML-документа должен выглядеть следующим образом:
<!DOCTYPE html> <html> <head> <style> body { background-color: #d24dff } </style> </head> </html>
-
5
Используйте «background-color», чтобы задать цвет фона других элементов (заголовков, абзацев и тому подобных). Например, чтобы задать цвет фона основного заголовка (<h1>) или абзаца (<p>), напишите следующий код:[2]
<!DOCTYPE html> <html> <head> <style> body { background-color: #93B874; } h1 { background-color: #00b33c; } p { background-color: #FFFFFF); } </style> </head> <body> <h1>Заголовок на зеленом фоне</h1> <p>Абзац на белом фоне</p> </body> </html>
Реклама
-
1
Найдите заголовок «html». Он должен быть в верхней части документа.
-
2
Запомните основной синтаксис этого процесса. Чтобы создать градиент, необходимо знать две величины: начальную точку/угол и ряд цветов, которые будут переходить один в другой. Можно выбрать несколько цветов, чтобы они переходили друг в друга; также можно задать направление или угол перехода. [3]
background: linear-gradient(направление/угол, цвет1, цвет2, цвет3 и так далее);
-
3
Создайте вертикальный градиент. Если не задать направление, градиент будет идти сверху вниз. Чтобы создать такой градиент, введите следующий код между тегами
<style></style>
:html { min-height: 100%; } body { background: -webkit-linear-gradient(#93B874, #C9DCB9); background: -o-linear-gradient(#93B874, #C9DCB9); background: -moz-linear-gradient(#93B874, #C9DCB9); background: linear-gradient(#93B874, #C9DCB9); background-color: #93B874; }
- В различных браузерах функции градиента реализованы по-разному, поэтому нужно добавить несколько версий кода.
-
4
Создайте направленный градиент. Если вы не хотите, чтобы градиент шел по вертикали, укажите направление перехода цветов. Для этого введите следующий код между тегами
<style></style>
:[4]
html { min-height: 100%; } body { background: -webkit-linear-gradient(left, #93B874, #C9DCB9); background: -o-linear-gradient(right, #93B874, #C9DCB9); background: -moz-linear-gradient(right, #93B874, #C9DCB9); background: linear-gradient(to right, #93B874, #C9DCB9); background-color: #93B874; }
- Если хотите, переставьте слова «left» (влево) и «right» (вправо), чтобы поэкспериментировать с разными направлениями градиента.
-
5
Используйте другие свойства для настройки градиента. С ним можно сделать больше, чем кажется.
- Например, после каждого цвета можно ввести число в процентах. Так вы укажите, какое пространство будет занимать каждый цветовой сегмент. Вот пример кода с такими параметрами:
background: linear-gradient(#93B874 10%, #C9DCB9 70%, #000000 90%);
- Добавьте прозрачность к цвету. В этом случае он будет постепенно затухать. Чтобы добиться эффекта затухания, используйте один и тот же цвет. Чтобы задать цвет, понадобится функция rgba(). Последнее значение определит прозрачность: 0 — непрозрачный цвет и 1 — прозрачный цвет.
background: linear-gradient(to right, rgba(147,184,116,0), rgba(147,184,116,1));
- Например, после каждого цвета можно ввести число в процентах. Так вы укажите, какое пространство будет занимать каждый цветовой сегмент. Вот пример кода с такими параметрами:
-
6
Просмотрите код. Код для создания цветового градиента в качестве фона веб-страницы будет выглядеть примерно так:
<!DOCTYPE html> <html> <head> <style> html { min-height: 100%; } body { background: -webkit-linear-gradient(left, #93B874, #C9DCB9); background: -o-linear-gradient(right, #93B874, #C9DCB9); background: -moz-linear-gradient(right, #93B874, #C9DCB9); background: linear-gradient(to right, #93B874, #C9DCB9); background-color: #93B874; } </style> </head> <body> </body> </html>
Реклама
-
1
Найдите заголовок «html». Он должен быть в верхней части документа.
-
2
Добавьте свойство «animation» в элемент «body». Введите следующий код после «body {» и до закрывающей фигурной скобки:[5]
-webkit-animation: colorchange 60s infinite; animation: colorchange 60s infinite;
- Верхняя строка текста предназначена для браузеров на основе Chromium, а нижняя строка текста — для других браузеров.
-
3
Добавьте цвета в свойство «animation». Воспользуйтесь правилом «@keyframes», чтобы задать цвета фона, которые будут циклически меняться, а также время, в течение которого каждый цвет будет отображаться на странице. Не забудьте ввести разный код для различных браузеров. Введите следующий код под закрывающей фигурной скобкой элемента «body»: [6]
@-webkit-keyframes colorchange { 0% {background: #33FFF3;} 25% {background: #78281F;} 50% {background: #117A65;} 75% {background: #DC7633;} 100% {background: #9B59B6;} } @keyframes colorchange { 0% {background: #33FFF3;} 25% {background: #78281F;} 50% {background: #117A65;} 75% {background: #DC7633;} 100% {background: #9B59B6;} }
- Обратите внимание, что два правила (@-webkit-keyframes и @keyframes) имеют одинаковые цвета фона и проценты. Это сделано для того, чтобы меняющийся фон правильно работал в любом браузере.
- Проценты (0%, 25% и так далее) обозначают долю от времени (60 с). Когда страница загрузится, ее фоном будет цвет #33FFF3. Когда пройдет 15 с (25% от 60 с), фон сменится на цвет # 7821F и так далее.
- Измените время и цвета, чтобы они соответствовали желаемому результату.
-
4
Просмотрите код. Код для создания меняющегося фона должен выглядеть следующим образом:
<!DOCTYPE html> <html> <head> <style> body { -webkit-animation: colorchange 60s infinite; animation: colorchange 60s infinite; } @-webkit-keyframes colorchange { 0% {background: #33FFF3;} 25% {background: #78281F;} 50% {background: #117A65;} 75% {background: #DC7633;} 100% {background: #9B59B6;} } @keyframes colorchange { 0% {background: #33FFF3;} 25% {background: #78281F;} 50% {background: #117A65;} 75% {background: #DC7633;} 100% {background: #9B59B6;} } </style> </head> <body> </body> </html>
Реклама
Советы
- Если вы хотите использовать основные цвета в HTML-коде, можно вводить имена цветов (без символа #), а не их числовые коды. Например, чтобы создать оранжевый фон, введите
background-color: orange;
. - В качестве фона веб-страницы можно установить изображение.
Реклама
Предупреждения
- Проверьте изменения, внесенные в код веб-сайта, прежде чем публиковать их.
Реклама
Источники
Об этой статье
Эту страницу просматривали 185 520 раз.
Была ли эта статья полезной?
Фон и границы
- Назад
- Обзор: Building blocks
- Далее
В этом уроке мы рассмотрим некоторые интересные возможности, которые вы можете сделать с помощью CSS-свойств фона и границ . Благодаря добавлению градиентов, фоновых изображений и закруглённых углов свойства фона и границ ответят на многие вопросы стилизации в CSS.
Необходимые умения: | Базовая компьютерная грамотность, основное программное обеспечение, понимание работы с файлами, базовые знания HTML (смотрите Введение в HTML) и представление о том, как работает CSS (смотрите Введение в CSS). |
---|---|
Цель: | Научиться стилизации фона и границ объектов. |
Стилизация фона в CSS
CSS-свойство background
является сокращением для ряда полных свойств фона, с которыми мы познакомимся в этом уроке. Если вы обнаружите сложное свойство background
в таблице стилей, это может показаться трудным для понимания, так как одновременно может быть передано так много значений.
.box {
background: linear-gradient(105deg, rgba(255,255,255,.2) 39%, rgba(51,56,57,1) 96%) center center / 400px 200px no-repeat,
url(big-star.png) center no-repeat, rebeccapurple;
}
Мы вернёмся к тому, как работает сокращение позже, а пока давайте взглянем на различные вещи, которые вы можете делать с фоном в CSS, посмотрев на отдельные свойства background
.
Фоновый цвет
Свойство background-color
определяет цвет фона для любого элемента в CSS. Свойство принимает любой допустимый цвет <color>
. background-color
распространяется на сам контент и отступы от него (padding).
В приведённом ниже примере мы использовали различные значения цвета, чтобы добавить цвет фона к блоку, заголовку и элементу <span>
.
Поиграйте с ними, используя любое доступное значение <color>.
Фоновое изображение
Свойство background-image
позволяет отображать изображение в качестве фона элемента. В приведённом ниже примере у нас есть два блока — в одном фоновое изображение больше, чем размеры блока, а в другом — маленькое изображение звезды.
Этот пример демонстрирует две особенности фоновых изображений. По умолчанию большое изображение не масштабируется до размера блока, поэтому мы видим только его небольшой угол, в то время как маленькое изображение повторяется, чтобы заполнить весь блок. В нашем случае фактически было использовано изображение одной маленькой звезды.
Примечание: Если кроме фонового изображения вы добавили фоновый цвет, то изображение будет отображаться над цветом. Попробуйте добавить свойство background-color
в приведённый выше пример, чтобы увидеть это в действии.
Свойство background-repeat
Свойство background-repeat
используется для управления повторениями фонового изображения. Доступные значения:
no-repeat
— останавливает повторение фонового изображения во всех направлениях.repeat-x
— повторение фонового изображения по горизонтали.repeat-y
— повторение фонового изображения по вертикали.repeat
— повторение фонового изображения в обоих направлениях. Установлено по умолчанию.
Попробуйте эти значения в примере ниже. Мы установили значение no-repeat
, поэтому вы видите только одну звезду. Попробуйте разные значения — repeat-x
и repeat-y
— чтобы увидеть, какие эффекты они оказывают.
Изменение размеров фонового изображения
В приведённом выше примере у нас есть большое изображение, которое в конечном итоге было обрезано, так как оно больше, чем элемент, фоном которого оно является. В этом случае мы могли бы использовать свойство background-size
, которое может принимать значения длины или в процентах, чтобы размер изображения соответствовал размеру фона.
Вы также можете использовать ключевые слова:
cover
— браузер сделает изображение достаточно большим, чтобы оно полностью заполнило блок, сохраняя при этом соотношение сторон. В этом случае часть изображения, скорее всего, окажется за пределами блока.contain
— браузер сделает изображение нужного размера, чтобы поместиться в блоке. В этом случае могут появиться пробелы с обеих сторон или сверху и снизу изображения, если соотношение сторон изображения отличается от соотношения сторон блока.
Ниже я применил значения длины к размерам изображения. Глядите, как это исказило изображение.
В приведённом ниже примере я использовал большое изображение из ранее рассмотренного примера и указал значения длины, чтобы определить его размер внутри блока. Вы можете посмотреть, как это исказило изображение.
Попробуйте следующее.
- Измените значения длины, используемые для изменения размера фона.
- Измените значение длины на
background-size: cover
илиbackground-size: contain
. - Если ваше изображение меньше размеров блока, вы можете изменить значение свойства
background-repeat
, чтобы повторить изображение.
Позиционирование фонового изображения
Свойство background-position
позволяет вам изменять позицию, в которой фоновое изображение появляется в блоке. При этом используется система координат, в которой левый верхний угол блока равен (0,0)
, а сам блок располагается вдоль горизонтальной (x
) и вертикальной (y
) осей.
Примечание: По умолчанию значение background-position
равно (0,0)
.
Обычно свойство background-position
задают в виде двух последовательных значений — значение по горизонтали, за которым следует значение по вертикали.
Вы можете использовать такие ключевые слова, как top
и right
(с остальными можете ознакомиться на странице background-position
):
.box {
background-image: url(star.png);
background-repeat: no-repeat;
background-position: top center;
}
Допустимы значения длины и процентные:
.box {
background-image: url(star.png);
background-repeat: no-repeat;
background-position: 20px 10%;
}
Вы также можете смешивать значения ключевых слов с длинами или процентами, например:
.box {
background-image: url(star.png);
background-repeat: no-repeat;
background-position: top 20px;
}
И наконец, вы также можете использовать синтаксис с четырьмя значениями, чтобы указать расстояние от определённых краёв блока — единица длины в данном случае представляет собой смещение от значения ключевого слова. Итак, в CSS ниже мы сместили фон на 20 пикселей сверху и на 10 пикселей справа:
.box {
background-image: url(star.png);
background-repeat: no-repeat;
background-position: top 20px right 10px;
}
Используйте приведённый ниже пример, чтобы поэкспериментировать с этими значениями и переместить звезду внутри блока.
Градиент в качестве фона
Градиент — при использовании для фона — действует так же, как изображение, и поэтому задаётся свойством background-image
.
Вы можете прочитать больше о различных типах градиентов и о том, что вы можете с ними делать на странице MDN для типа данных <gradient>
. Поиграть с градиентами вы можете используя один из многих генераторов градиентов CSS, доступных в Интернете, например этот. Вы можете создать градиент, а затем скопировать и вставить его в свой код.
Попробуйте использовать разные градиенты в примере ниже. В двух блоках соответственно у нас есть линейный градиент, растянутый на весь блок, и радиальный градиент с заданным размером, который поэтому повторяется.
Несколько фоновых изображений
Также возможно создавать несколько фоновых изображений — просто разделив значения свойства background-image
запятыми.
Когда вы сделаете это, произойдёт наложение фоновых изображений друг на друга. Фоновые изображения будут наложены слоями, где каждое новое фоновое изображение, перечисленное в коде, будет накладываться поверх ранее указанного изображения.
Примечание: Градиенты можно легко смешивать с обычными фоновыми изображениями.
Другие свойства background- *
также могут иметь значения, разделённые запятыми, как и background-image
:
background-image: url(image1.png), url(image2.png), url(image3.png), url(image1.png);
background-repeat: no-repeat, repeat-x, repeat;
background-position: 10px 20px, top right;
Каждое значение различных свойств будет соответствовать значениям в той же позиции в других свойствах. Выше, например, значение background-repeat
для image1
будет no-repeat
. Однако, что происходит, когда разные свойства имеют разное количество значений? Ответ заключается в том, что меньшее количество значений будет циклически повторяться — в приведённом выше примере есть четыре фоновых изображения, и только два значения background-position
. Первые два значения позиции будут применены к первым двум изображениям, затем они снова будут циклически повторяться — image3
будет присвоено первое значение позиции, а image4
будет присвоено второе значение позиции.
Поиграем? В приведённом ниже примере я добавил два изображения. Чтобы продемонстрировать порядок наложения, попробуйте поменять порядок фоновых изображений в списке. Или поиграйте с другими свойствами, чтобы изменить положение, размер или повторяемость значений.
Закрепление фона
Другая опция, которую можно применить к фону, — это указать, как он будет прокручиваться при прокрутке содержимого. Это контролируется с помощью свойства background-attachment
, которое может принимать следующие значения:
scroll
: Заставляет элементы фона прокручиваться при прокрутке страницы. Если содержимое элемента прокручивается, фон не перемещается. Фактически, фон фиксируется в той же позиции на странице, поэтому он прокручивается по мере прокрутки страницы.fixed
: Фиксирует элементы фона в области просмотра, чтобы он не прокручивался при прокрутке страницы или содержимого элемента. Фон всегда будет оставаться на одном и том же месте на экране.local
: Это значение было добавлено позже (оно поддерживается только в Internet Explorer 9+, тогда как другие поддерживаются в IE4+), потому что значениеscroll
довольно запутанно и во многих случаях действительно не делает то, что вы хотите. Значениеlocal
фиксирует фон для элемента, к которому он применён, поэтому, когда вы прокручиваете элемент, фон прокручивается вместе с ним.
Свойство background-attachment
действует только тогда, когда есть контент для прокрутки, поэтому мы сделали пример, чтобы продемонстрировать различия между тремя значениями — взгляните на background-attachment.html (также смотри исходный код здесь).
Использование сокращённого свойства background
Как я упоминал в начале этого урока, вы часто будете видеть фон, заданный с помощью свойства background
. Это сокращение позволяет вам одновременно устанавливать все различные свойства.
При использовании нескольких фонов необходимо указать все свойства для первого фона, а затем добавить следующий фон после запятой. В приведённом ниже примере у нас есть градиент с размером и положением, затем фоновое изображение со значением no-repeat
и положением, затем цвет.
При записи сокращённых значений фонового изображения необходимо соблюдать несколько правил, например:
background-color
можно указывать только после последней запятой.- Значения
background-size
могут быть включены только сразу послеbackground-position
, разделённые символом ‘/’, например:center/80%
.
Посетите страницу MDN свойства
, чтобы увидеть полное описание.
Доступность просмотра
Помещая текст поверх фонового изображения или цвета, вы должны позаботиться о том, чтобы у вас было достаточно контраста, чтобы текст был читаемым для посетителей вашего сайта. Если указывается изображение, и текст будет помещён поверх этого изображения, вы также должны указать background-color
, который позволит тексту быть разборчивым, если изображение не загружается.
Программы чтения с экрана не могут анализировать фоновые изображения, поэтому они должны быть чисто декоративными; любой важный контент должен быть частью HTML-страницы, а не находиться в фоне.
Границы
Изучая Блочную модель, мы обнаружили, как границы влияют на размер нашего блока. В этом уроке мы рассмотрим, как творчески использовать границы. Обычно, когда мы добавляем границы к элементу с помощью CSS, мы используем сокращённое свойство, которое устанавливает цвет, ширину и стиль границы в одной строке CSS.
Мы можем установить границу для всех четырёх сторон блока с помощью border
:
.box {
border: 1px solid black;
}
Или мы можем нацеливаться на один край блока, например:
.box {
border-top: 1px solid black;
}
Индивидуальные свойства этих сокращений будут следующими:
.box {
border-width: 1px;
border-style: solid;
border-color: black;
}
И более детально:
.box {
border-top-width: 1px;
border-top-style: solid;
border-top-color: black;
}
Примечание: Свойства границ top, right, bottom, и left также имеют сопоставленные логические свойства, которые относятся к режиму написания документа (например, текст слева направо, справа налево или сверху вниз). Мы рассмотрим их в следующем уроке, который касается работы с разными направлениями текста.
Есть множество стилей, которые вы можете использовать для границ. В приведённом ниже примере мы использовали разные стили границ для четырёх сторон моего блока. Поиграйте со стилем, шириной и цветом границы, чтобы увидеть, как они работают.
Закруглённые углы
Закругление углов блока достигается с помощью свойства border-radius
и связанных свойств, которые относятся к каждому углу блока. В качестве значения могут использоваться два значения длины или процента: первое значение определяет горизонтальный радиус, а второе — вертикальный радиус. Чаще задают только одно значение, которое используется для обоих.
Например, чтобы сделать все четыре угла блока радиусом 10px:
.box {
border-radius: 10px;
}
Или, чтобы верхний правый угол имел горизонтальный радиус 1em и вертикальный радиус 10%:
.box {
border-top-right-radius: 1em 10%;
}
В примере ниже мы установили все четыре угла, а затем изменили значения для верхнего правого угла, чтобы сделать его другим. Вы можете поиграть со значениями, чтобы изменить углы. Взгляните на страницу свойств для border-radius
чтобы увидеть доступные варианты синтаксиса.
Упражнение с границами и фоном
Чтобы проверить свои новые знания, попробуйте создать следующее, используя фон и границы, используя приведённый ниже пример в качестве отправной точки:
- Задайте рамку равную 5px black solid, с закруглёнными углами 10px.
- Добавить фоновое изображение (используйте URL
balloons.jpg
) и установите размер таким образом, чтобы он покрыл весь блок. - Задайте для
<h2>
полупрозрачный чёрный цвет фона и сделайте текст белым.
Примечание: вы можете посмотреть решение здесь — но сначала попробуйте сделать это сами!
Итоги
В этой теме мы рассмотрели довольно много, но как вы можете увидеть, возможностей по стилизации фона или границ блока намного больше. Изучите различные страницы свойств, если хотите узнать больше о каких-либо функциях, которые мы обсуждали. На каждой странице MDN есть много примеров использования свойств, с которыми вы можете поиграть и расширить свои знания.
В следующем уроке мы узнаем, как Режим написания вашего документа взаимодействует с вашим CSS. Что происходит, если текст не перетекает слева направо?
- Назад
- Обзор: Building blocks
- Далее
В этом модуле
При вёрстке страниц веб-сайта часто требуется задать фон определённому объекту для улучшения читаемости текста и внешнего вида портала в целом. Какими способами и методами можно задавать фон в CSS?
- Работа с фоном в CSS
- background-color
- background-image
- background-repeat
- background-attachment
- background-position
- gradient
- Работа с размером фона в CSS
- Абсолютное изменение размера
- Относительное изменение размера
- Масштабирование до максимального размера
- Заполнение фоном
- Масштабирование сразу нескольких фонов
- Создание полупрозрачного фона в CSS
С помощью свойства background можно задать положение, цвет, изображение, повторяемость и привязку фона, как для отдельных элементов, так и полностью для всего сайта, что по своей сути, кстати, является заданием определённых настроек для тега <body>. Рассмотрим все свойства, которые связаны с заданием фона.
Задаёт цвет фона. Его можно применять как к отдельным элементам <h1>, <p>, так и ко всему веб-сайту с помощью тега <body>.
Например:
/* белый фон заголовка и чёрный цвет шрифта h1 { color: #000; background-color: #fff }
Данное свойство используется для вставки фоновой картинки, указывая при этом ссылку на неё.
Например:
body { background-image: url(“example_image.png”); }
Обратите внимание на то, как указан путь к картинке. Это значит, что изображение должно находиться в той же директории, что и файл стилей CSS. Иначе придётся указывать полный путь к файлу.
Изображение из предыдущего примера будет повторяться по всему экрану благодаря данному свойству.
Оно может иметь несколько значений:
- background-repeat: repeat-x — повторение по горизонтали;
- background-repeat: repeat-y — повторение по вертикали;
- background-repeat: repeat — повторение и по горизонтали и по вертикали;
- background-repeat: no-repeat — изображение не повторяется.
Например, повторение по горизонтали выглядит так:
Это свойство определяет фиксирование фонового изображения при скроллинге:
- background-attachment: scroll — фон прокручивается вместе со страницей;
- background-attachment: fixed — фон остаётся неподвижным.
Данное свойство определяет расположение фоновой картинки относительно экрана. Значения свойства представляют собой набор вертикальных и горизонтальных координат, отсчет которых начинается с верхнего левого угла.
Свойство может задаваться в процентном формате, в пикселях, сантиметрах или словесно: top, bottom, center, right, left.
Например:
- background-position: 50% 20% — изображение располагается по центру по горизонтали и на 20% отступает сверху;
- background-position: 80px 60px — отступ изображения вниз на 80 пикселей от верхнего края и на 60 пикселей вправо от левого:
Плавный переход от одного цвета к другому, причем переходов допускается несколько.
Использование градиента можно наглядно продемонстрировать в примере кода:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Градиент</title> <style> .gradient { background: #2639fa; /* Для устаревших браузеров */ background: linear-gradient(to top, #2639fa, #c9d1ff); padding: 40px; border: 1px solid #000; } </style> </head> <body> <p class="gradient">текст</p> </body> </html>
Все приведённые настройки можно сделать в одном свойстве background, записав их в перечисленном порядке.
Например:
background: #fff url(“example_image.png”) no-repeat fixed right bottom
Если пропустить какое-либо свойство, для него устанавливается значение по умолчанию.
В CSS 2.1 фоновая картинка сохраняет фиксированный размер, однако в CSS 3 было введено подсвойство size, благодаря которому фоновое изображение может быть растянуто или сжато.
Существует несколько способов, позволяющих определить размер:
Ширина и высота по умолчанию устанавливаются автоматически, а новый размер можно задать с помощью различных единиц измерения.
Например, если исходное изображение имеет разрешение 300 на 300 пикселей, то такой код сделает его ширину в два раза меньше:
background-size: 150px 300px
Если указано только одно значение, оно по умолчанию считается как ширина, высота определяется автоматически, и пропорции сохраняются.
Код, который масштабирует картинку до размера 100 на 100 пикселей, выглядит так:
Если применять проценты, размер будет основываться не на изображении, а на элементе.
Например:
background-size: 50% auto;
То есть, ширина фонового изображения зависит от параметров контейнера. Если ширина контейнера составляет 600 пикселей, размер фонового изображения уменьшится до величины 300 на 300 пикселей.
Как показывает практика, использование процентов весьма полезно для адаптивного дизайна.
В свойстве background-size значение contain масштабирует фоновое изображение так, чтобы оно полностью заполняло контейнер или всю страницу.
Уменьшение или увеличение происходит пропорционально до тех пор, пока высота или ширина не будет выходить за рамки контейнера.
Такой фон страницы будет автоматически подгоняться под любое разрешение:
background-size: contain;
Используя в свойстве background-size значение cover, фон масштабируется таким образом, чтобы заполнить всё пространство контейнера.
В том случае, если соотношения сторон различаются, картинка обрежется:
Они могут быть масштабированы при помощи списка значений, которые разделены запятыми в том же порядке:
background: url(“example_image.png”) 70% 90% no-repeat, url(“example_image.png”) 30% 50% no-repeat, url(“example_image.png”) 15% 25% no-repeat #fff, url(“example_image.png”) 70% 90% no-repeat, background-size: 250px 200px, auto, 100 px;
Полупрозрачный элемент хорошо заметен на фоновом рисунке. В веб-дизайне полупрозрачность достигается за счёт свойства opacity или задаваемого для фона формата цвета RGBA.
Особенность данного свойства заключается в том, что прозрачность действует не только на фон, но и на все дочерние элементы. После увеличения прозрачности, и текст и фон станут полупрозрачными.
Пример создания полупрозрачного блока:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>opacity</title> <style> body { background: url("http://cs614726.vk.me/v614726246/4a02/300wj_aFOK4.jpg"); background-size: 10% auto; } div { opacity: 0.7; background: #717ceb; /* Цвет фона */ padding: 20px; /* Поля вокруг текста */ } </style> </head> <body> <div>Так выглядит полупрозрачный блок.</div> </body> </html>
Однако достаточно часто полупрозрачным должен быть только фон определённого элемента, а текст оставаться непрозрачным для читабельности.
В таком случае opacity не подходит и следует воспользоваться форматом RGBA, в котором помимо значений яркости синего, красного и зелёного цветов устанавливается ещё и значение прозрачности. 1 означает абсолютную непрозрачность, а 0 — полную прозрачность.
Пример задания прозрачного фона:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>rgba</title> <style> body { background: url("http://cs614726.vk.me/v614726246/4a02/300wj_aFOK4.jpg"); background-size: 20% auto; } div { background: rgba(60, 150, 250, 0.7); /* Цвет фона */ color: #fff; /* Цвет текста */ padding: 20px; /* Поля вокруг текста */ } </style> </head> <body> <div>Прозрачный фон блока и непрозрачный текст.</div> </body> </html>
Надеемся, что данное руководство вам пригодилось, и желаем успехов в освоении веб-дизайна!
Download Article
An easy-to-follow guide for coding with CSS and HTML to add the background colors of a page
Download Article
- Setting a Solid Background Color
- Creating a Gradient Background
- Creating a Changing Background
- Q&A
- Tips
- Warnings
|
|
|
|
|
Did you want to change the background color of that page using HTML? Unfortunately, with HTML 5, this is no longer possible in just HTML coding. Instead, you’ll need to use both HTML and CSS coding, which works even better. This wikiHow teaches you how to change the background color of a web page by editing its HTML and CSS.
Things You Should Know
- Although the attribute for HTML to manage background color is gone, you can still use HTML with CSS to change your background color easily.
- You’ll need a numeric code for the color you want if you want a specific color. If you don’t need a specific color, you can use words like «orange» or «light blue.»
- When editing a web page with HTML and CSS, you can create a solid background, gradient, or changing background.
-
1
Find your document’s «html» header. It should be near the top of the document.
-
2
Add the «background-color» property to the «body» element. Type
background-color:
between the body brackets. You should now have the following «body» element:- In this context, only one spelling of «color» will work; you can’t use «colour» here.
body { background-color: }
Advertisement
-
3
Add your desired background color to the «background-color» property. Type your selected color’s numeric code followed by a semicolon next to the «background-color:» element to do so. For example, to set your page’s background to pink, you would have the following:
body { background-color: #d24dff; }
-
4
Review your «style» information. At this point, your HTML document’s header should resemble the following:
<!DOCTYPE html> <html> <head> <style> body { background-color: #d24dff } </style> </head> </html>
-
5
Use «background-color» to apply background colors to other elements. Just as you set it in the body element, you can use «background-color» to define the backgrounds of other elements such as headers, paragraphs, and so on. For example, to apply a background color to a main header (<h1>) or a paragraph (<p>), you would have something resembling the following code:[1]
<!DOCTYPE html> <html> <head> <style> body { background-color: #93B874; } h1 { background-color: #00b33c; } p { background-color: #FFFFFF); } </style> </head> <body> <h1>Header with Green Background</h1> <p>Paragraph with white background</p> </body> </html>
Advertisement
-
1
Find your document’s «html» header. It should be near the top of the document.
-
2
Understand the basic syntax of this process. When making a gradient, there are two pieces of information you’ll need: the starting point/angle, and the colors that the gradient will transition between. You can select multiple colors to have the gradient move between all of them, and you can set a direction or angle for the gradient.[2]
background: linear-gradient(direction/angle, color1, color2, color3, etc);
}}
-
3
Make a vertical gradient. If you don’t specify the direction, the gradient will go from top to bottom. To create your gradient, add the following code between the
<style></style>
tags:- Different browsers have different implementations of the gradient function, so you’ll have to include several versions of the code.
html { min-height: 100%; } body { background: -webkit-linear-gradient(#93B874, #C9DCB9); background: -o-linear-gradient(#93B874, #C9DCB9); background: -moz-linear-gradient(#93B874, #C9DCB9); background: linear-gradient(#93B874, #C9DCB9); background-color: #93B874; }
-
4
Make a directional gradient. If you’d rather create a gradient that isn’t strictly vertical, you can add direction to the gradient in order to change the way the color shift appears. Do so by typing the following in between the
<style></style>
tags:[3]
- You can play around with the «left» and «right» tags to experiment with different directions for your gradient.
html { min-height: 100%;} body { background: -webkit-linear-gradient(left, #93B874, #C9DCB9); background: -o-linear-gradient(right, #93B874, #C9DCB9); background: -moz-linear-gradient(right, #93B874, #C9DCB9); background: linear-gradient(to right, #93B874, #C9DCB9); background-color: #93B874; }
-
5
Use other properties to adjust the gradient. There’s a lot more that you can do with gradients.
- For example, not only can you add more than two colors, you can also put a percentage after each one. This will allow you to set how much spacing you want each color segment to have. Here’s a sample gradient that uses this principle:
background: linear-gradient(#93B874 10%, #C9DCB9 70%, #000000 90%);
- For example, not only can you add more than two colors, you can also put a percentage after each one. This will allow you to set how much spacing you want each color segment to have. Here’s a sample gradient that uses this principle:
-
6
Add transparency to your colors. This will make the color fade. Use the same color to fade from the color to nothing. You’ll need to use the rgba() function to define the color. The ending value determines the transparency: 0 for solid and 1 for transparent.
background: linear-gradient(to right, rgba(147,184,116,0), rgba(147,184,116,1));
-
7
Review your completed code. The code to create a color gradient as your website’s background will look something like this:
<!DOCTYPE html> <html> <head> <style> html { min-height: 100%; } body { background: -webkit-linear-gradient(left, #93B874, #C9DCB9); background: -o-linear-gradient(right, #93B874, #C9DCB9); background: -moz-linear-gradient(right, #93B874, #C9DCB9); background: linear-gradient(to right, #93B874, #C9DCB9); background-color: #93B874; } </style> </head> <body> </body> </html>
Advertisement
-
1
Find your document’s «html» header. It should be near the top of the document.
-
2
Add the animation property to the «body» element. Type the following into the space below the «body {» bracket and above the closing bracket:[4]
- The top line of text is for Chromium-based browsers while the bottom line of text is for other browsers.
-webkit-animation: colorchange 60s infinite; animation: colorchange 60s infinite;
-
3
Add your colors to the animation. Now you’ll use the @keyframes rule to set the background colors through which you’ll cycle, as well as the length of time each color will appear on the page. Again, you’ll need separate entries for the different sets of browsers. Enter the following lines of code below the closed «body» bracket:[5]
- Note that the two rules (@-webkit-keyframes and @keyframes have the same background colors and percentages. You’ll want these to stay uniform so the experience is the same on all browsers.
- The percentages (0%, 25%, etc) are of the total animation length (60s). When the page loads, the background will be the color set at 0% (#33FFF3). Once the animation has played for 25% of of 60 seconds, the background will turn to #7821F, and so on.
- You can modify the times and colors to fit your desired outcome.
@-webkit-keyframes colorchange { 0% {background: #33FFF3;} 25% {background: #78281F;} 50% {background: #117A65;} 75% {background: #DC7633;} 100% {background: #9B59B6;} } @keyframes colorchange { 0% {background: #33FFF3;} 25% {background: #78281F;} 50% {background: #117A65;} 75% {background: #DC7633;} 100% {background: #9B59B6;} }
-
4
Review your code. Your entire code for the changing background color should resemble the following:
<!DOCTYPE html> <html> <head> <style> body { -webkit-animation: colorchange 60s infinite; animation: colorchange 60s infinite; } @-webkit-keyframes colorchange { 0% {background: #33FFF3;} 25% {background: #78281F;} 50% {background: #117A65;} 75% {background: #DC7633;} 100% {background: #9B59B6;} } @keyframes colorchange { 0% {background: #33FFF3;} 25% {background: #78281F;} 50% {background: #117A65;} 75% {background: #DC7633;} 100% {background: #9B59B6;} } </style> </head> <body> </body> </html>
Advertisement
Add New Question
-
Question
How do I set a background color for a specific width?
Use the background-size property inside of the «body» element. For example, «background-size: 300px 150px» makes the background 300 pixels wide and 150 pixels high.
-
Question
It does not work. What can I do?
UsernameHere11
Community Answer
To make it black, try:
body {
background-color: #190707} -
Question
What is the correct HTML for adding a background color?
My text goes here!
Replace the html code above with your text and selected your preferred color.
See more answers
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
-
Use online HTML pickers if you want a very specific color for your background. If, for example, you want the background to be the same color as your walls, you can match HTML colors with paint splotches at certain sites.
-
If you want to use basic colors within your HTML code, you can type the colors’ names without the pound sign (#) instead of using an HTML color code. For example: to create an orange background, you would type in
background-color: orange;
here.
Show More Tips
Thanks for submitting a tip for review!
Advertisement
-
Make sure you test any changes to your website before publishing them online.
Advertisement
References
About This Article
Thanks to all authors for creating a page that has been read 1,491,185 times.
Is this article up to date?
Download Article
An easy-to-follow guide for coding with CSS and HTML to add the background colors of a page
Download Article
- Setting a Solid Background Color
- Creating a Gradient Background
- Creating a Changing Background
- Q&A
- Tips
- Warnings
|
|
|
|
|
Did you want to change the background color of that page using HTML? Unfortunately, with HTML 5, this is no longer possible in just HTML coding. Instead, you’ll need to use both HTML and CSS coding, which works even better. This wikiHow teaches you how to change the background color of a web page by editing its HTML and CSS.
Things You Should Know
- Although the attribute for HTML to manage background color is gone, you can still use HTML with CSS to change your background color easily.
- You’ll need a numeric code for the color you want if you want a specific color. If you don’t need a specific color, you can use words like «orange» or «light blue.»
- When editing a web page with HTML and CSS, you can create a solid background, gradient, or changing background.
-
1
Find your document’s «html» header. It should be near the top of the document.
-
2
Add the «background-color» property to the «body» element. Type
background-color:
between the body brackets. You should now have the following «body» element:- In this context, only one spelling of «color» will work; you can’t use «colour» here.
body { background-color: }
Advertisement
-
3
Add your desired background color to the «background-color» property. Type your selected color’s numeric code followed by a semicolon next to the «background-color:» element to do so. For example, to set your page’s background to pink, you would have the following:
body { background-color: #d24dff; }
-
4
Review your «style» information. At this point, your HTML document’s header should resemble the following:
<!DOCTYPE html> <html> <head> <style> body { background-color: #d24dff } </style> </head> </html>
-
5
Use «background-color» to apply background colors to other elements. Just as you set it in the body element, you can use «background-color» to define the backgrounds of other elements such as headers, paragraphs, and so on. For example, to apply a background color to a main header (<h1>) or a paragraph (<p>), you would have something resembling the following code:[1]
<!DOCTYPE html> <html> <head> <style> body { background-color: #93B874; } h1 { background-color: #00b33c; } p { background-color: #FFFFFF); } </style> </head> <body> <h1>Header with Green Background</h1> <p>Paragraph with white background</p> </body> </html>
Advertisement
-
1
Find your document’s «html» header. It should be near the top of the document.
-
2
Understand the basic syntax of this process. When making a gradient, there are two pieces of information you’ll need: the starting point/angle, and the colors that the gradient will transition between. You can select multiple colors to have the gradient move between all of them, and you can set a direction or angle for the gradient.[2]
background: linear-gradient(direction/angle, color1, color2, color3, etc);
}}
-
3
Make a vertical gradient. If you don’t specify the direction, the gradient will go from top to bottom. To create your gradient, add the following code between the
<style></style>
tags:- Different browsers have different implementations of the gradient function, so you’ll have to include several versions of the code.
html { min-height: 100%; } body { background: -webkit-linear-gradient(#93B874, #C9DCB9); background: -o-linear-gradient(#93B874, #C9DCB9); background: -moz-linear-gradient(#93B874, #C9DCB9); background: linear-gradient(#93B874, #C9DCB9); background-color: #93B874; }
-
4
Make a directional gradient. If you’d rather create a gradient that isn’t strictly vertical, you can add direction to the gradient in order to change the way the color shift appears. Do so by typing the following in between the
<style></style>
tags:[3]
- You can play around with the «left» and «right» tags to experiment with different directions for your gradient.
html { min-height: 100%;} body { background: -webkit-linear-gradient(left, #93B874, #C9DCB9); background: -o-linear-gradient(right, #93B874, #C9DCB9); background: -moz-linear-gradient(right, #93B874, #C9DCB9); background: linear-gradient(to right, #93B874, #C9DCB9); background-color: #93B874; }
-
5
Use other properties to adjust the gradient. There’s a lot more that you can do with gradients.
- For example, not only can you add more than two colors, you can also put a percentage after each one. This will allow you to set how much spacing you want each color segment to have. Here’s a sample gradient that uses this principle:
background: linear-gradient(#93B874 10%, #C9DCB9 70%, #000000 90%);
- For example, not only can you add more than two colors, you can also put a percentage after each one. This will allow you to set how much spacing you want each color segment to have. Here’s a sample gradient that uses this principle:
-
6
Add transparency to your colors. This will make the color fade. Use the same color to fade from the color to nothing. You’ll need to use the rgba() function to define the color. The ending value determines the transparency: 0 for solid and 1 for transparent.
background: linear-gradient(to right, rgba(147,184,116,0), rgba(147,184,116,1));
-
7
Review your completed code. The code to create a color gradient as your website’s background will look something like this:
<!DOCTYPE html> <html> <head> <style> html { min-height: 100%; } body { background: -webkit-linear-gradient(left, #93B874, #C9DCB9); background: -o-linear-gradient(right, #93B874, #C9DCB9); background: -moz-linear-gradient(right, #93B874, #C9DCB9); background: linear-gradient(to right, #93B874, #C9DCB9); background-color: #93B874; } </style> </head> <body> </body> </html>
Advertisement
-
1
Find your document’s «html» header. It should be near the top of the document.
-
2
Add the animation property to the «body» element. Type the following into the space below the «body {» bracket and above the closing bracket:[4]
- The top line of text is for Chromium-based browsers while the bottom line of text is for other browsers.
-webkit-animation: colorchange 60s infinite; animation: colorchange 60s infinite;
-
3
Add your colors to the animation. Now you’ll use the @keyframes rule to set the background colors through which you’ll cycle, as well as the length of time each color will appear on the page. Again, you’ll need separate entries for the different sets of browsers. Enter the following lines of code below the closed «body» bracket:[5]
- Note that the two rules (@-webkit-keyframes and @keyframes have the same background colors and percentages. You’ll want these to stay uniform so the experience is the same on all browsers.
- The percentages (0%, 25%, etc) are of the total animation length (60s). When the page loads, the background will be the color set at 0% (#33FFF3). Once the animation has played for 25% of of 60 seconds, the background will turn to #7821F, and so on.
- You can modify the times and colors to fit your desired outcome.
@-webkit-keyframes colorchange { 0% {background: #33FFF3;} 25% {background: #78281F;} 50% {background: #117A65;} 75% {background: #DC7633;} 100% {background: #9B59B6;} } @keyframes colorchange { 0% {background: #33FFF3;} 25% {background: #78281F;} 50% {background: #117A65;} 75% {background: #DC7633;} 100% {background: #9B59B6;} }
-
4
Review your code. Your entire code for the changing background color should resemble the following:
<!DOCTYPE html> <html> <head> <style> body { -webkit-animation: colorchange 60s infinite; animation: colorchange 60s infinite; } @-webkit-keyframes colorchange { 0% {background: #33FFF3;} 25% {background: #78281F;} 50% {background: #117A65;} 75% {background: #DC7633;} 100% {background: #9B59B6;} } @keyframes colorchange { 0% {background: #33FFF3;} 25% {background: #78281F;} 50% {background: #117A65;} 75% {background: #DC7633;} 100% {background: #9B59B6;} } </style> </head> <body> </body> </html>
Advertisement
Add New Question
-
Question
How do I set a background color for a specific width?
Use the background-size property inside of the «body» element. For example, «background-size: 300px 150px» makes the background 300 pixels wide and 150 pixels high.
-
Question
It does not work. What can I do?
UsernameHere11
Community Answer
To make it black, try:
body {
background-color: #190707} -
Question
What is the correct HTML for adding a background color?
My text goes here!
Replace the html code above with your text and selected your preferred color.
See more answers
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
-
Use online HTML pickers if you want a very specific color for your background. If, for example, you want the background to be the same color as your walls, you can match HTML colors with paint splotches at certain sites.
-
If you want to use basic colors within your HTML code, you can type the colors’ names without the pound sign (#) instead of using an HTML color code. For example: to create an orange background, you would type in
background-color: orange;
here.
Show More Tips
Thanks for submitting a tip for review!
Advertisement
-
Make sure you test any changes to your website before publishing them online.
Advertisement
References
About This Article
Thanks to all authors for creating a page that has been read 1,491,185 times.
Is this article up to date?
Setting the background color of a web page or an element on the page can enable you to create unique layouts.
Take the homepage of Delish as an example. The background image of its header section is a colorful soup. To ensure readers can still see the name of the recipe, the background color of the text box is set to white. The effect is striking and easy to read.
In the past, you could use the background color attribute to change the background color of a page or element.
Say you wanted to change the background color of a web page to maroon. You would have simply added the bgcolor attribute in the opening body tag and set it to the hex color code #800000, as shown below.
<body bgcolor=”#800000">
However, this attribute has been deprecated in the latest version of HTML and replaced by a much better alternative, the CSS background-color property. Using this property, you can add and change background colors on your website.
Let’s go through how you can change background color in HTML. We’ll cover:
- Adding a background color in HTML
- Changing the background color in HTML
- Changing the background color of a div
- Choosing how to write your HTML color codes
- Adding transparency to a background color
- Creating a gradient background color
- Frequently asked questions
To add background color in HTML, use the CSS background-color property. Set it to the color name or code you want and place it inside a style attribute. Then add this style attribute to an HTML element, like a table, heading, div, or span tag.
Adding a background color can help a certain element stand out on the page, making it more readable.
We’ll walk through this process step-by-step. For this tutorial, we’ll make a table in HTML as an example.
1. Identify the HTML element you’d like to add a background to or create one.
Scan your HTML code to pinpoint which element you’d like to change. If it’s the header, look for the <header> opening tag. If it’s a div, look for the <div> tag.
In this example, we’re creating a table with the <table> tag.
2. Choose an HTML background color.
You have plenty of HTML color codes to choose from. For this example, we’ll make the color #33475b.
3. Add a style attribute to the opening tag.
Next, add the style attribute to the opening tag of your element. For this tutorial, only the background color of this specific table will change. The change will not affect any other element on the page.
Here’s the HTML with inline CSS:
<table style="background-color:#33475b">
<tr>
<th>Name</th>
<th>Job Title</th>
<th>Email address</th>
</tr>
<tr>
<td>Anna Fitzgerald</td>
<td>Staff Writer</td>
<td>example@company.com</td>
</tr>
<tr>
<td>John Smith</td>
<td>Marketing Manager</td>
<td>example2@company.com</td>
</tr>
<tr>
<td>Zendaya Grace</td>
<td>CEO</td>
<td>example2@company.com</td>
</tr>
</table>
That’s simple. Now let’s look at what to do if you want to set the background color of multiple elements on a page.
How to Change Background Color in HTML
Let’s say you set the background color of your entire web page to one color and want to change the background color of a specific element to another color. The good news is the process for changing the background color of an element is nearly identical to the process for adding it.
You can use inline CSS to do this, but we’ll use multiple styles of CSS in the example below. Let’s walk through this process step-by-step.
1. Find the “body” CSS selector.
Rather than add this CSS in the body tag of the HTML file, we’ll add it using the body CSS selector. Find it in your website’s CSS code.
2. Change the background color of the body.
Next, we’ll change the background color of the entire web page using the background-color property.
Here’s the CSS:
body {
background-color: #DBF9FC;
}
Here’s the result:
If this was the only CSS, then everything on the page would have the same light blue background. Next, we’ll add inline CSS to change the background color of the table.
3. Add inline CSS to change the background color of specific elements.
If we want to change the background color of the table, we can use inline CSS to target that single element.
Here’s the opening tag with inline CSS:
<table style="background-color:#33475b">
Here’s the result:
How to Change a Div Background Color
A div is a container element that’s commonly used to designate different sections of a webpage.
Changing the background color of a div is identical to changing the background color of your web page’s body.
Usually, a web page will have many divs. In this tutorial, we’ll teach you how to change one div only.
Let’s go through the process step-by-step.
1. Add a CSS class to the div you’d like to change.
First, find the div in your HTML code and add a class to the opening tag. Adding a class to an element will allow you to change that element only.
Here’s what that looks like:
<div class=”example”>This is a div on a webpage. </div>
2. Add the new class selector to your CSS code.
Next, head over to your CSS code and add your new class selector. Within the brackets, include the background-color property.
Here’s what that looks like:
.example {background-color: ; }
3. Choose a new background color.
Next, choose a CSS background color for your background-color property. We chose rgb(255, 122, 89).
Here’s what that code looks like:
.example { background-color: rgb(255, 122, 89); }
Here’s the result:
All done! You’ve changed the background of a div on your web page.
Learn More: The Beginner’s Guide to HTML & CSS
Want to learn more about HTML? Download our free guide for best practices for getting started with HTML.
Background Color HTML Codes
In this post, we’ve been using color codes (more specifically, hex color codes) to add colors to the backgrounds of our page elements. But, there are actually a few ways to specify your background colors. Next, let’s review the different ways you can write colors in CSS.
Background Color Hex Codes
Hex codes are the most popular format for adding color to page elements in HTML. A hex code is a hexadecimal (base 16) number preceded by a hash symbol (#).
Every hex code contains six characters, and each pair of characters determines the intensity of the three primary colors (red, green, and blue in that order) from 00 (lowest intensity) to FF (highest intensity).
For example, the color white is the highest intensity of all three colors, so its hex code is #FFFFFF. Black is the opposite — the lowest intensity of all colors, or #000000. For the color green, we crank up the intensity for green and lower it for red and blue, giving us the hex code #00FF00. HubSpot’s signature shade of orange, Solaris, has the hex code #FF5C35.
If you do the math, this comes out to 16,777,216 possible hex codes. Fortunately, you don’t need to guess which color works best for your background. You can use an HTML color picker like this one to select a color from a spectrum, then simply copy the hex code it gives you.
Image Source
Background Color Names
Hex values aren’t too difficult to understand, but there’s an even simpler way to add color in HTML: simply use the name of a color.
Modern browsers support 140 standardized HTML color names, including simple ones like Red, Green, Blue, Yellow, Orange, etc. There are also more precise hues like DarkRed, SpringGreen, SkyBlue, Khaki, and Coral.
Check out a color reference like this one for a list of all HTML color names and their corresponding hex and RGB codes. When you find a color value you like, use it as the value of your background-color property (no # symbol necessary).
body {
background-color: SpringGreen;
}
Background Color RGB Codes
We can also create HTML color values with RGB (red green blue) notation. Like hex codes, RGB values allow us to target a color value by specifying its red, green, and blue intensity.
To add color with RGB, we use the rgb() CSS function. This function takes three values inside the parentheses, each specifying the intensity of red, green, and blue in the color. Each value is a number from 0 to 255, with 0 being the least intense and 255 being the most intense.
For example, the RGB function for Solaris orange in CSS is rgb(255, 92, 53):
body {
background-color: rgb(255, 92, 53);
}
HTML color pickers will also provide RGB values along with hex codes, so this is the easiest way to find the RGB code you need. There are also plenty of hex-to-RGB converters online, like this one.
Alternatively, you can set an opacity level of your color with the CSS function rgba(). The “a” stands for alpha channel, which represents the level of transparency in a color. This function takes one extra value from 0 to 1, where 0 is completely transparent and 1 is completely opaque.
So, if I wanted to use Solaris with 75% transparency, I’d write the following:
body {
background-color: rgba(255, 92, 53, 0.75);
}
Background color HSL Values
Finally, you can use HSL values to set your colors in CSS. HSL, which stands for hue, saturation, and lightness, is written with the hsl() function. The syntax is similar to RGB, except you use percentages to indicate the saturation and lightness of the hue you pick.
To create Solaris with HSL, for example, use the function hsl(12, 100%, 60%).
body {
hsl(12, 100%, 60%);
}
You can also specify an alpha channel value with the function hsl(), which accepts an additional value from 0 to 1 and sets the transparency of the color.
How to Add Transparency to Your HTML Background Color
When changing background color in HTML, you aren’t limited to solid colors. You can change the opacity and transparency to create interesting visual effects.
To do that, you’d use the opacity property in CSS.
What’s the CSS opacity property?
The CSS opacity property is added to an HTML element (such as a div or a table) or a CSS attribute (such as a class) to make those elements partially or fully transparent. Values for this property range from 0 to 1, with 0 being completely transparent and 1 being completely opaque.
For this tutorial, we’ll use two buttons as an example. Let’s walk through the process of adding transparency step-by-step.
1. Identify the HTML elements you’d like to make transparent.
If you already know what you want to change, go ahead and find it in your HTML code.
In this tutorial, we have two Bootstrap buttons side by side. We want visitors to click one — the submit button — and not click the other — the “no thanks” option.
Here’s the HTML:
<button class="btn" type="submit">Submit</button>
<button class="btn" type="submit">No thanks</button>
We want to decrease the opacity of the latter to make it seem deactivated and drive fewer clicks.
To achieve this result, we’ll use the CSS opacity property after adding a class to the button we’ll change.
2. Add a class to the element you’d like to change.
Next, we’ll assign an additional CSS class to the second button to distinguish it from the first.
We’ll add the class btn-secondary to the button we want to deemphasize.
Here’s what that looks like:
<button class="btn" type="submit">Submit</button>
<button class="btn btn-secondary" type="submit">No thanks</button>
3. Add the class selector to your CSS code and apply the opacity property.
Now that you’ve created a new class, it’s time to add it to your CSS code.
To make the second button 40% see-through, we’ll use the .btn-secondary class selector to apply the opacity property. Then, we’ll set the opacity level to 0.4.
Here’s the CSS:
.btn-secondary {
opacity: 0.4;
}
Here’s the result:
You may have noticed we did not need to use the CSS background-color property because we used Bootstrap’s default modifier classes.
Learn more about Bootstrap in The Ultimate Guide to Bootstrap CSS.
How to Create an HTML Background Color Gradient
For even more style options, you can create a gradient background. This is a special type of image that most commonly shows one color gradually changing to another color in a certain direction like top to bottom, left to right, or diagonally.
These are known as linear gradients. To create a linear gradient, you have to specify at least two color stops.
Let’s look at four quick examples below.
Linear Gradient Tutorial — Top to Bottom
Say you want your background color to transition from white at the top of the screen to blue at the bottom.
Using the body CSS selector, you’ll apply unique style properties to the body of the web page. Here’s what that looks like from beginning to end.
- Step 1: Find the body selector in your CSS code.
- Step 2: Your body might already have a background-color property. Delete that. Rather than use the background-color property, you’ll use the background-image property.
- Step 3: Set the property to “linear-gradient” and specify two color stops in parentheses. Here’s the syntax:
body { background-image: linear-gradient(color, color); }
- Step 4: Next, you want to set the HTML element’s height to 100% to ensure this image takes up the entire screen.
All together, here’s the CSS:
html {
height: 100%;
}
body {
background-image: linear-gradient(#FFFFFF, rgb(255, 122, 89));
}
Here’s the HTML (including the body tags):
<body>
<h1>Linear Gradient</h1>
<p>This linear gradient starts as white at the top and transitions to orange at the bottom.</p>
</body>
Here’s the result:
Linear Gradient — Left to Right
No direction was specified for the linear gradient above. That’s because top to bottom is the default direction.
If you’d like to specify another direction, then you’ll add it in the parentheses, before the color stops.
Here’s the CSS for the example above, rewritten so the gradient is left to right.
html {
height: 100%;
}
body {
background-image: linear-gradient(to right, #FFFFFF, rgb(255, 122, 89));
}
Here’s the HTML:
<body>
<h1>Linear Gradient</h1>
<p>This linear gradient starts as white at the left and transitions to orange at the right.</p>
</body>
Here’s the result:
Linear Gradient — 45° Angle
If I wanted the gradient to go diagonally, then I could use the keywords “to bottom right,” “to bottom left,” “to top right,” or “to top left.” If you’d like more control over the direction of your gradient, then you could use angles rather than keywords.
Note that a value of 0 degrees is equivalent to the keyword «to top,” 90 degrees is equivalent to «to right,” and 180 degrees is equivalent to «to bottom.”
If I wanted the gradient to go to the top right, for example, then I could set the direction to 45deg.
Here’s the CSS:
html {
height: 100%;
}
body {
background-image: linear-gradient(45deg, #FFFFFF, rgb(255, 122, 89));
}
Here’s the HTML:
<body>
<h1>Linear Gradient</h1>
<p>This linear gradient starts as white at the bottom left and transitions to orange at the top right.</p>
</body>
Here’s the result:
Linear Gradient — Multiple Color Stops
To create a linear gradient, you need a minimum of two color stops. But there’s no maximum, which means you can use as many as you want. Below is an example with four color stops.
Here’s the CSS:
html {
height: 100%;
}
body {
background-image: linear-gradient(to bottom right, #33475b, #0033CC, #FF77CC, rgb(255, 122, 89));
}
Here’s the HTML:
<body>
<h1>Linear Gradient</h1>
<p>This linear gradient starts as dark blue at the top left and transitions from pink to orange at the bottom right.</p>
</body>
Here’s the result:
FAQs: Changing Background Color in HTML
Still have questions? We have answers for you.
How do you change text background color in HTML?
You can change the background color of text in HTML by adding a background-color property to a paragraph (p) or heading (H1, H2, H3… ) element.
Add this property either via inline CSS or on your website’s CSS code.
What is the default background color in HTML?
The default background color in HTML is transparent.
How do I make a background color transparent?
You can make a background color fully or partially transparent by using an RGBA color code to define the background-color property.
Here’s what that looks like in CSS:
background-color: rgba(255, 255, 255, 0);
The last value determines transparency. Be sure that it’s set to 0 if you want the color to be completely invisible.
How do I remove background color in HTML?
You can fully remove background color by setting the background-color property to “transparent.”
Here’s what that looks like in CSS:
background-color: transparent;
Changing Your Background Color with HTML & CSS
Using HTML and CSS, you can add background color to your web page or different elements on the page. This background color can be solid, transparent, or gradient depending on the style that you like. This basic web design knowledge can enable you to customize your website and make your content more readable and engaging.
Editor’s note: This post was originally published in September 2020 and has been updated for comprehensiveness.