Как изменить фон формы html

I'm trying to set a background color to the HTML form tag, but it doesn't work?! I thought it was a simple task! #form { background-color: #000; padding: 10px; }

I’m trying to set a background color to the HTML form tag, but it doesn’t work?! I thought it was a simple task!

#form {
    background-color: #000;
    padding: 10px;
}

Peter Mortensen's user avatar

asked Jul 22, 2011 at 7:33

3D-kreativ's user avatar

3D-kreativ3D-kreativ

8,88135 gold badges100 silver badges158 bronze badges

5

You can use an inline style:

<form style="background-color:#E6E6FA">
<input type="submit" value="ClickMe" >
</form>

JSFiddle Example

Jacob G's user avatar

Jacob G

13.5k3 gold badges47 silver badges67 bronze badges

answered Jul 14, 2014 at 20:08

user3817445's user avatar

1

Can we just see the HTML code of your form? Maybe there’s a class you’re using that conflicts with your #form declaration.

Also, if you want the «form block» to have a background, put it inside a div and background it.

If you want to give a background to the form inputs, you should give a style to the input objects

#form input{
  background-color: #000;
}

#form input .submit{ ... }

#form label { ... }

And so on.

Peter Mortensen's user avatar

answered Jul 22, 2011 at 7:49

Samuele Mattiuzzo's user avatar

1

You should post the HTML content, but if you want to set the style sheet for the form «tag», you should not use #. instead do something like:

form {background:#000000;}

«#» is applied for the elements with the appended id, and the style sheet you have written works for an element like
< div id=»form» >etc…< /div >

Peter Mortensen's user avatar

answered Jul 22, 2011 at 7:58

Arash Kazemi's user avatar

Arash KazemiArash Kazemi

1,1883 gold badges15 silver badges30 bronze badges

I had the same problem. The form had fieldset tags in it, and those had the style float:left. This caused the background-color not to be rendered. Without the float it worked.

Peter Mortensen's user avatar

answered Jun 22, 2018 at 21:07

Frank Thuerigen's user avatar

If you want no background in your form then set the background to none:

<form style="background:none">

Peter Mortensen's user avatar

answered Nov 28, 2018 at 11:04

batman21's user avatar

For background colors in a form, notify the form control in the form tag and provide this form field in the style tag as shown below.

form {
  background-color: #FFC;
} 

Peter Mortensen's user avatar

answered Feb 25, 2020 at 13:39

Rahul Jai sharma's user avatar

1

I found a solution to this on CodePen. If the input tags are wrapped in a fieldset within the form, then adding a background-color to the fieldset works perfectly. Like this:

body {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

fieldset {
  background-color: powderblue;
  border: none;
}

input, label {
  display: block;
  margin: 1em;
  border: none;
}
<form action="">
  <fieldset>
    <label for="">Full Name</label>
    <input type="text">
    <label for="">Enter email</label>
    <input type="text" email="">
    <input type="submit" value="Submit">
  </fieldset>
</form>

answered Dec 3, 2021 at 22:54

Fiona Farrier's user avatar

Серёжа Сыроежкин

Серёжа СыроежкинКопирайтер

Фон для сайта 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. Изображение с названием 2609629 1 2

    1

    Определите цвет фона, который вы хотите использовать. В HTML цвета задаются кодами, которые определяют различные оттенки. Воспользуйтесь бесплатным онлайн-инструментом W3Schools HTML Color Picker, чтобы найти коды нужных цветов:

    • Перейдите на страницу https://www.w3schools.com/colors/colors_picker.asp в веб-браузере компьютера.
    • Выберите базовый цвет, который хотите использовать, в разделе «Pick a Color» (Выбрать цвет).
    • Выберите оттенок в правой части страницы.
    • Запишите код, который отобразится справа от выбранного оттенка.
  2. Изображение с названием 2609629 2 2

    2

    Откройте HTML-файл в текстовом редакторе. Помните, что в HTML5 атрибут <bgcolor> больше не поддерживается. Поэтому цвет фона и другие параметры стиля страницы задаются с помощью CSS.[1]

    • HTML-документ можно открыть в Notepad++ или Блокноте (Windows), а также в TextEdit или BBEdit (Mac).
  3. Изображение с названием 2609629 3 2

    3

    Добавьте заголовок «html» в документ. Все параметры стиля страницы, включая цвет фона, должны находиться между тегами <style></style>:

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    </style> 
    </head>
    </html>
    
  4. 4

    Создайте пустую строку между тегами «style». На этой строке, которая должна находиться под тегом <style> и над тегом </style>, вы введете необходимую информацию.

  5. 5

    Изображение с названием 2609629 4 2

  6. Изображение с названием 2609629 5 2

    6

    Добавьте элемент «body». Введите следующий код между тегами <style></style>:

    • Все, что будет заключено внутри элемента «body» в CSS, повлияет на всю страницу.
    • Пропустите этот шаг, если хотите создать градиентный фон.

    Реклама

  1. Изображение с названием 2609629 6 2

    1

    Найдите заголовок «html». Он должен быть в верхней части документа.

  2. Изображение с названием 2609629 7 2

    2

    Добавьте свойство «background-color» в элемент «body». Введите background-color: в фигурных скобках внутри элемента «body». Должен получиться следующий код:

    body {
        background-color: 
    }
    
    • Обратите внимание, что в этом коде необходимо использовать слово «color», а не «colour».
  3. Изображение с названием 2609629 8 3

    3

    Добавьте нужный цвет фона в свойство «background-color». Справа от «background-color:» введите числовой код выбранного цвета, а затем введите точку с запятой (;). Например, чтобы фон страницы сделать розовым, напишите следующий код:

    body {
        background-color: #d24dff;
    }
    
  4. Изображение с названием 2609629 9 2

    4

    Просмотрите информацию внутри тегов «style». На этом этапе заголовок вашего HTML-документа должен выглядеть следующим образом:

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    body {
    background-color: #d24dff
    }
    </style>
    </head>
    </html>
    
  5. Изображение с названием 2609629 10 2

    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. Изображение с названием 2609629 11 2

    1

    Найдите заголовок «html». Он должен быть в верхней части документа.

  2. Изображение с названием 2609629 12 2

    2

    Запомните основной синтаксис этого процесса. Чтобы создать градиент, необходимо знать две величины: начальную точку/угол и ряд цветов, которые будут переходить один в другой. Можно выбрать несколько цветов, чтобы они переходили друг в друга; также можно задать направление или угол перехода. [3]

    background: linear-gradient(направление/угол, цвет1, цвет2, цвет3 и так далее);
    
  3. Изображение с названием 2609629 13 2

    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. Изображение с названием 2609629 14 2

    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. Изображение с названием 2609629 15 2

    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. Изображение с названием 2609629 16 2

    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. Изображение с названием 2609629 17 2

    1

    Найдите заголовок «html». Он должен быть в верхней части документа.

  2. Изображение с названием 2609629 18 2

    2

    Добавьте свойство «animation» в элемент «body». Введите следующий код после «body {» и до закрывающей фигурной скобки:[5]

        -webkit-animation: colorchange 60s infinite; 
        animation: colorchange 60s infinite;
    
    • Верхняя строка текста предназначена для браузеров на основе Chromium, а нижняя строка текста — для других браузеров.
  3. Изображение с названием 2609629 19 2

    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. Изображение с названием 2609629 20 2

    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 раз.

Была ли эта статья полезной?


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. Image titled 2609629 1 3

    1

    Find your document’s «html» header. It should be near the top of the document.

  2. Image titled 2609629 2 3

    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:

      body {
          background-color: 
      }
      
    • In this context, only one spelling of «color» will work; you can’t use «colour» here.

    Advertisement

  3. Image titled 2609629 3 3

    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. Image titled 2609629 4 3

    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. Image titled 2609629 5 3

    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>
      
  6. Advertisement

  1. Image titled 2609629 6 3

    1

    Find your document’s «html» header. It should be near the top of the document.

  2. Image titled 2609629 7 3

    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. Image titled 2609629 8 4

    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:

      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; }
      
    • Different browsers have different implementations of the gradient function, so you’ll have to include several versions of the code.
  4. Image titled 2609629 9 3

    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]

      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; }
      
    • You can play around with the «left» and «right» tags to experiment with different directions for your gradient.
  5. Image titled 2609629 10 3

    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%);
      
  6. Image titled 2609629 11 3

    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. Image titled 2609629 12 3

    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>
      
  8. Advertisement

  1. Image titled 2609629 13 3

    1

    Find your document’s «html» header. It should be near the top of the document.

  2. Image titled 2609629 14 3

    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]

          -webkit-animation: colorchange 60s infinite; 
          animation: colorchange 60s infinite;
      
    • The top line of text is for Chromium-based browsers while the bottom line of text is for other browsers.
  3. Image titled 2609629 15 3

    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]

      @-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;}
      }
      
    • 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.
  4. Image titled 2609629 16 3

    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>
      
  5. Advertisement

Add New Question

  • Question

    How do I set a background color for a specific width?

    Community Answer

    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

    UsernameHere11

    Community Answer

    To make it black, try:

    body {
    background-color: #190707}

  • Question

    What is the correct HTML for adding a background color?

    Community Answer

    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. Image titled 2609629 1 3

    1

    Find your document’s «html» header. It should be near the top of the document.

  2. Image titled 2609629 2 3

    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:

      body {
          background-color: 
      }
      
    • In this context, only one spelling of «color» will work; you can’t use «colour» here.

    Advertisement

  3. Image titled 2609629 3 3

    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. Image titled 2609629 4 3

    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. Image titled 2609629 5 3

    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>
      
  6. Advertisement

  1. Image titled 2609629 6 3

    1

    Find your document’s «html» header. It should be near the top of the document.

  2. Image titled 2609629 7 3

    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. Image titled 2609629 8 4

    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:

      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; }
      
    • Different browsers have different implementations of the gradient function, so you’ll have to include several versions of the code.
  4. Image titled 2609629 9 3

    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]

      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; }
      
    • You can play around with the «left» and «right» tags to experiment with different directions for your gradient.
  5. Image titled 2609629 10 3

    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%);
      
  6. Image titled 2609629 11 3

    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. Image titled 2609629 12 3

    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>
      
  8. Advertisement

  1. Image titled 2609629 13 3

    1

    Find your document’s «html» header. It should be near the top of the document.

  2. Image titled 2609629 14 3

    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]

          -webkit-animation: colorchange 60s infinite; 
          animation: colorchange 60s infinite;
      
    • The top line of text is for Chromium-based browsers while the bottom line of text is for other browsers.
  3. Image titled 2609629 15 3

    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]

      @-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;}
      }
      
    • 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.
  4. Image titled 2609629 16 3

    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>
      
  5. Advertisement

Add New Question

  • Question

    How do I set a background color for a specific width?

    Community Answer

    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

    UsernameHere11

    Community Answer

    To make it black, try:

    body {
    background-color: #190707}

  • Question

    What is the correct HTML for adding a background color?

    Community Answer

    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.

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]

Changing the background color in HTML can make elements stand out

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>

HTML table with a navy background color and white font color

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:

Page with light aqua background color and a table with the default transparent background

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:

Web page with a light aqua background color and a navy blue table

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:

Image showing two divs with different background colors

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

Learn More: The Beginner’s Guide to HTML & CSS

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.

an html hex color picker to change the background color in HTML

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:

Two Bootstrap buttons, one of which has transparency

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 as a background color in an HTML web page

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:

Left-to-right linear gradient background on a web page

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:

45-degree linear gradient background on a web page

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:

HTML background gradient with blue, pink, and orange color stops

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.

coding templates

Как сделать фон в HTML

От автора: всех приветствую. Фоновые цвета и изображения в веб-дизайне имеют огромную роль, так как позволяют более привлекательно оформить любые элементы. Как сделать фон в html, мы рассмотрим сегодня.

Можно ли обойтись средствами html при задании фона?

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

Соответственно, мы будем использовать каскадные таблицы стилей (css). Там гораздо больше возможностей для задания бэкграунда. Мы сегодня разберем самые основные.

Как задать фон через css?

Итак, прежде всего вам нужно определиться с тем, какому элементу нужно задать фон. То есть нам нужно найти селектор, к которому мы будем писать правило. Например, если фон нужно задать всей странице в целом, то можно сделать это через селектор body, всем блокам – через селектор div. Ну и т.д. Фон можно и нужно привязывать к любым другим селекторам: стилевым классам, идентификаторам и т.д.

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

Узнать подробнее

После того, как вы определились с селектором, нужно написать само название свойства. Для задания фонового цвета (именно сплошного цвета, не градиента и не картинки) используется свойство background-color. После него нужно поставить двоеточие и написать сам цвет. Это можно сделать по-разному. Например, с помощью ключевых слов, hex-кода, форматов rgb, rgba, hsl. Любой способ подойдет.

Чаще всего используется способ шестнадцатеричного кода. Для подбора цветов можно использовать программу, в которой видно код цвета. Например, photoshop, paint или какой-либо онлайн-инструмент. Соответственно, для примера пропишу общий фон для всей веб-страницы.

body{

backgroundcolor: #D4E6B3;

}

Я советую вам сейчас создать на рабочем столе html и css файлы, подключить css к html и повторять за мной. Так вы поймете все намного лучше, чем если просто читать. Для работы с файлами советую использовать программу Notepad++. Назовите первый файл, например index.html, а второй — style.css. Подключить css к html можно так:

<link rel = «stylesheet» href = «style.css»>

Этот код нужно вставить в секцию head. Важно, чтобы файлы находились в одной папке.

Хорошо, а мы идем дальше. Чтобы показать вам другие возможности задания фона, мне придется создать небольшой блок, в котором мы и будем экспериментировать с фоновым изображением. Да-да, именно с изображением.

Картинка в качестве фона

В качестве картинки я буду использовать маленький значок языка html:

Создадим пустой блок с идентификатором:

Зададим ему явные размеры и фон:

#bg{

width: 400px;

height: 250px;

backgroundimage: url(html.png);

}

Из этого кода вы можете видеть, что я использовал новое свойство – background-image. Оно предназначено как раз для вставки картинки в качестве фона html-элементу. Посмотрим, что получилось:

Чтобы задать картинку, вы должны после двоеточия написать ключевое слово url, а потом в круглых скобках указать путь к файлу. В данном случае путь указан исходя из того, что изображение лежит в той же папке, что и html-документ. Также нужно указать формат изображения.

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

Но заметили ли вы одну особенность? Браузер взял и размножил картинку по всему блоку. Так вот, чтобы вы знали, это поведение фоновых картинок по умолчанию – они повторяются по вертикали и горизонтали до тех пора, пока могут влезь в блок. По этим поведением вы можете легко управлять. Для этого используют свойство background-repeat, у которого есть 4 основных значения:

Repeat – значение по умолчанию, изображение повторяется по обеим сторонам;

Repeat-x – повторяется только по оис x;

Repeat-y – повторяется только по оси y;

No-repeat – не повторяется вообще;

Каждое значение вы можете прописать и посмотреть, что же случится. Я пропишу так:

backgroundrepeat: repeatx;

Теперь повторение только по горизонтали. Если прописать no-repeat, то была бы только одна картинка.

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

С помощью повторения верстальщики раньше достигали того, что создавали фоновые текстуры и градиенты, используя одно малюсенькое изображение. Оно могло быть 30 на 10 пикселей или еще меньше. А может и немного больше. Изображение было таким, что при его повторении по одной или даже по обеим сторонам, не было видно переходов, так что в итоге получался единый цельный фон. К слову, такой подход стоит использовать и сейчас, если вы хотите использовать бесшовную текстуру на своем сайте в качестве фона. Градиент же сегодня уже можно реализовать методами css3, об этом мы еще обязательно поговорим.

Позиция фона

По умолчанию фоновое изображение, если для него не задано повторение, будет находиться в левом верхнем углу своего блока. Но положение можно легко изменить с помощью свойства background-position.

Задавать его можно по-разному. Один из вариантов, это просто указать стороны в которых должна находиться картинка:

backgroundposition: right top;

То есть по вертикали все так и осталось: фоновая картинка располагается сверху, но по горизонтали мы изменили сторону на right, то есть правую. Еще один способ задать позицию – в процентах. Отсчет при этом начинается в любом случае с верхнего левого угла. 100% — весь блок. Таким образом, чтобы поместить картинку ровно по центру, запишем так:

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

Узнать подробнее

backgroundposition: 50% 50%;

Запомните одну важную вещь, связанную с позиционированием – первым параметром всегда указывается позиция по горизонтали, а вторым – по вертикали. Итак, если вы видите значение 80% 20%, то можно сразу заключить, что фоновое изображение будет сильно сдвинуто вправо, но вниз при этом сильно не уйдет.

Ну и наконец, прописывать позицию можно в пикселях. Все то же самое, только вместо % будет px. В некоторых случаях может понадобиться и такое позиционирование.

Сокращенная запись

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

background: #333 url(bg.jpg) no-repeat 50% 50%;

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

Далее мы рассмотрим другое свойство – размер фона. Его уже не задашь сокращенно в качестве параметров в сокращенной записи.

Управляем размером фоновой картинки

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

Как можно поступить в таком случае? Конечно, самым простым и разумным вариантом будет просто уменьшение картинки, но не всегда есть возможность это сделать. Допустим, она лежит на сервере и в данный момент нет времени и возможности ее уменьшить. Проблему можно решить с помощью свойства background-size, которое можно назвать относительно новым и которое позволяет манипулировать размером фонового изображения, да и вообще любого фона.

Итак, моя картинка сейчас занимает все пространство в блоке, но я задам ей размер фона:

backgroundsize: 80% 50%;

Опять же, первым параметром задается размер по горизонтали, вторым – по вертикали. Мы видим, что все правильно применилось –фото стало размером на 80% ширины блока в ширину и наполовину в высоту. Тут только нужно внести одно уточнение – задавая размер в процентах вы можете повлиять на пропорции картинки. Так что будьте внимательны, если хотите не нарушить пропорции.

Как вы можете догадаться, также размер фона можно указывать в пикселях. Еще есть два ключевых слова-значения, которые также можно использовать:

Cover – произойдет масштабирование картинки таким образом, чтобы хотя бы по одной стороне она полностью заполняла блок.

Contain – отмасштабирует так, чтобы картинка полностью влезала в блок в максимальном своем размере.

Преимущества этих значений в том, что они не изменяют пропорции картинки, оставляя их прежними.

Также вы должны понимать, что растягивание картинки может привести к ухудшению ее качества. Могу привести пример из жизни и реальной практики верстальщиков. Все знают и понимают, что при верстке под десктопы нужно адаптировать сайт под основные ширины мониторов: 1280, 1366, 1920. Если вы возьмете фоновую картинку размером, допустим, 1280 на 200, и не зададите ей background-size, то экранах с шириной больше появится пустое место, картинка не будет заполнять ширину полностью.

В 99% случаев это не устраивает веб-разработчика, поэтому он задает background-size: cover, чтобы картинка всегда тянулась на максимум по ширине окна. Это хороший прием, который нужно использовать, но теперь вы столкнетесь с проблемой, что пользователи с шириной экрана 1920 пикселей могут увидеть картинку неоптимального качества.

Я напомню, она растянется на максимум по ширине. Соответственно, качество автоматически ухудшится. Единственно правильным решением тут будет изначально использовать картинку большего размера – 1920 пикселей в ширину. Тогда на самых широких экранах она будет в своем натуральном размере, а на других просто будет потихоньку обрезаться, но при этом, при грамотном подборе фоновой картинки, на внешний вид сайта это не повлияет.

В общем, это всего лишь 1 пример того, как использовать знания, полученные вами в этой статье, при верстке реальных макетов.

Полупрозрачный фон с помощью css

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

Для примера я задам всей странице в качестве фона картинку, которую мы использовали ранее в примерах. Блоку же с идентификатором bg, на котором мы проводим все наши эксперименты, зададим фон с помощью формата задания цвета rgba.

Как я уже и говорил ранее, в css есть много форматов для задания цвета. Один из них – rgb, достаточно известный формат тем, кто работает в графических редакторах. Он записывается так:rgb(17, 255, 34);

Первым значением в скобках идет насыщенность красного, потом зеленого, потом синего. Значение может быть числовым от 0 до 255. Соответственно, формат rgba ничем не отличается, только добавляется еще один параметр – альфа-канал. Значение может быть от 0 до 1, где 0 – полная прозрачность.

Соответственно, для задания средней полупрозрачности нужно записать примерно так:

background: rgba(15, 17, 156, 0.5);

Зададим такой фоновый цвет блоку, вот что получится:

Как задать фон тексту?

До этих пор мы с вами рассматривали задание фона для блочных элементов. Но что, если вам нужно задать фон именно тексту? Решение тут очень простое: фон нужно прописать строчному элементу, в котором написан текст. Значит, в первую очередь нужно создать этот строчный элемент. По умолчанию для этих целей советую использовать span.

<div id = «bg»>

<span>Текст, к которому применим фон</span>

</div>

Это нужно нам с вами лишь для того, чтобы иметь возможность в css обратиться к нашему спану, чтобы мы сейчас благополучно и сделаем:

#bg span{

backgroundcolor: white;

}

Проверяем:

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

Больше возможностей в создании и управлении фоном

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

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

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

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

Узнать подробнее

Верстка. Быстрый старт

Практический курс по верстке адаптивного сайта с нуля!

Смотреть

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить фон файлов на рабочем столе
  • Как изменить фон установки windows 10
  • Как изменить фон уведомлений на андроид
  • Как изменить фон только на одном слайде
  • Как изменить фон только для одного слайда

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии