Меняем фон сайта с помощью HTML — Нубекс

Фон в HTML

Фон для сайта HTML можно изменить как с помощью атрибутов тега body, так и с помощью CSS-стилей, примененных также к тегу body. Рассмотрим оба варианта как сделать фон для сайта.

Меняем цвет фона с помощью HTML

Тег body, как и практически любой HTML-тег имеет свои атрибуты. К атрибутам тега body относятся:

  • bgcolor — определяет цвет фона для страницы;
  • background — позволяет задать картинку в качестве фона веб-страницы (подробно этот вопрос рассмотрен в статье: Как сделать фон сайта картинкой HTML);
  • scroll — управляет отображением полосы прокрутки на странице;
  • text — задает базовый цвет текста, который будет выводиться на веб-странице;
  • bgproperties — указывает, будет ли прокручиваться фон вместе со страницей;
  • link — управляет цветом ссылок по умолчанию на странице;
  • alink — устанавливает цвет для активной ссылки;
  • vlink — определяет цвет для посещенной ссылки на странице;
  • leftmargin/rightmargin — задает отступ контента от левого или правого края окна браузера;
  • topmargin/bottommargin — задает отступ контента от верхнего или нижнего края окна браузера;

Чтобы изменить цвет фона с помощью HTML, воспользуемся атрибутом bgcolor:

    

Это пример текста белого цвета, заданного с помощью атрибута text тега body.

Примечание: Рекомендуется определять цвет фона страницы, даже если фон белый. Это связано с тем, что некоторые пользователи могут использовать в браузере нестандартный цвет фона, и из-за этого текст на вашем сайте может быть нечитабельным.

Меняем цвет фона страницы с помощью CSS

Во избежании избыточности кода, рекомендуется всё, что связано с оформлением страницы, переносить на плечи CSS. К этому числу относится и задание цвета фона. CSS фон задается следующим образом:

   body 

Это пример текста белого цвета, заданного с помощью background CSS. Фон страницы также задан с помощью CSS.

В конструкторе сайтов «Нубекс» для любого сайта можно выбрать уже готовый фон из большой билиотеки изображений, или добавить свой.

Источник

Цвет фона

Цвет фона является достаточно важным элементом любой веб-страницы. Во-первых, он задает нужное настроение и общий настрой сайта, а во-вторых, облегчает восприятие текста.

Читайте также:  Граф дерево в питоне

Цвет фона веб-страницы задается с использованием атрибута bgcolor тега .

Пример 1. Изменение цвета фона

Цвет можно указывать в шестнадцатеричном значении или по его имени.

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

Фоновый рисунок

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

Пример 2. Добавление фонового рисунка

Если изображение меньше размера экрана монитора, оно будет размножено по горизонтали и вертикали.

Поскольку фоновый рисунок загружается медленнее, чем цвет фона, может получиться, что текст не будет читаться некоторое время, пока не произойдет загрузка рисунков. То же самое может случиться и при отключенных в браузере рисунках. Поэтому рекомендуется всегда задавать цвет фона наряду с фоновым рисунком (пример 3).

Пример 3. Использование фонового рисунка и цвета фона

Фиксированный фон

По умолчанию, при использовании полосы прокрутки, фоновый рисунок перемещается вместе с содержимым веб-страницы. Internet Explorer позволяет сделать фон неподвижным с помощью атрибута bgproperties =» fixed » тега .

Пример 4. Задание фиксированного фона

При указании атрибута bgproperties , как показано в примере 4, фоновый рисунок на веб-странице будет оставаться неподвижным, а текст, рисунки и другие элементы станут перемещаться вместе с полосой прокрутки.

Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.

Популярные материалы

  • Самоучитель HTML4
  • Самоучитель CSS
  • Как добавить картинку на веб-страницу?
  • Спецсимволы
  • Структура HTML-кода
  • Введение в HTML
  • Способы добавления стилей на страницу
  • Выравнивание текста
  • Якоря
  • Как добавить иконку сайта в адресную строку браузера?
  • Позиционирование элементов
  • Ссылки

Источник

How to Add & Change Background Color in HTML

Setting the background color of a web page or an element on the page can enable you to create unique layouts.

Person adding and changing the background color of a website in html

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.

Download Now: 25 HTML & CSS Hacks [Free Guide]

Free Guide: 25 HTML & CSS Coding Hacks

Tangible tips and coding templates from experts to help you code better and faster.

  • Coding to Convention
  • Being Browser-Friendly
  • Minimizing Bugs
  • Optimizing Performance

You’re all set!

Click this link to access this resource at any time.

HTML Background Color

In HTML and CSS, background color is denoted by the background-color property. To add or change background color in HTML, simply add inline CSS to your code. Here’s an example:

In the past, you could use the bgcolor 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.

Читайте также:  Html windows media classic

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.

Below, we cover a tutorial in more detail.

How to Add Background Color in HTML

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 opening tag. If it’s a div, look for the 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.

Free Guide: 25 HTML & CSS Coding Hacks

Tangible tips and coding templates from experts to help you code better and faster.

  • Coding to Convention
  • Being Browser-Friendly
  • Minimizing Bugs
  • Optimizing Performance

You’re all set!

Click this link to access this resource at any time.

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:

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:

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:

Here’s the result:

Image showing two divs with different background colors

All done! You’ve changed the background of a div on your web page.

Try It Yourself!

The code module below is editable. Toggle between the HTML and CSS tabs, edit the code, and click rerun in the bottom right-hand corner.

Free Guide: 25 HTML & CSS Coding Hacks

Tangible tips and coding templates from experts to help you code better and faster.

  • Coding to Convention
  • Being Browser-Friendly
  • Minimizing Bugs
  • Optimizing Performance
Читайте также:  Execute application from php

You’re all set!

Click this link to access this resource at any time.

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.

Adding Transparency Using RGBA

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:

Try It Yourself!

The code module below is editable. Toggle between the HTML and CSS tabs, edit the code, and click rerun in the bottom right-hand corner.

Free Guide: 25 HTML & CSS Coding Hacks

Tangible tips and coding templates from experts to help you code better and faster.

  • Coding to Convention
  • Being Browser-Friendly
  • Minimizing Bugs
  • Optimizing Performance

You’re all set!

Click this link to access this resource at any time.

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:
  • 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:

Here’s the HTML (including the body tags):

Linear Gradient

This linear gradient starts as white at the top and transitions to orange at the bottom.

Here’s the result:

Linear gradient as a background color in an HTML web page

Try It Yourself!

The code module below is editable. Toggle between the HTML and CSS tabs, edit the code, and click rerun in the bottom right-hand corner.

Free Guide: 25 HTML & CSS Coding Hacks

Tangible tips and coding templates from experts to help you code better and faster.

  • Coding to Convention
  • Being Browser-Friendly
  • Minimizing Bugs
  • Optimizing Performance

You’re all set!

Click this link to access this resource at any time.

Источник

Оцените статью