Как поменять цвет фона на сайте html
In this article, we will see how to set the background color of an element. The purpose of using style attribute is to add styles to the elements. Using style attribute with different elements results in change in that element only. This attribute can be used as inline, internal or external. The style attribute provides number of properties which can be used to improve a simple html page.
The background color can be changed in three ways:
- Inline style attribute
- Internal CSS
- External CSS
The HTML5 doesn’t support the ‘bgcolor’ attribute of <body> tag, therefore we need to use the inline style attribute and internal CSS options for changing the color of a web page. For internal CSS add <style> tag at beginning of html file and add the tag to which the changes are being applied in this case the <body> tag is used.
Syntax:
Example 1: Below is the example that illustrates the use of inline CSS.
How to Set Background Color with HTML and CSS
First thing you should know is that there are different types of HTML colors, such as Hex color codes, HTML color names, RGB and RGBa values, HSL colors, etc. To choose your preferred color use our Color Tools.
In this snippet, you can find many different ways of adding a background color. Let’s start from the easiest one.
Add the style attribute to the <body> element
You can set a background color for an HTML document by adding style=»background-color:» to the <body> element.
Example of setting a background color with the style attribute:
Result
Some paragraph for example.
Add the CSS background-color property to the <body> element
The background-color property is used to change the background color. Inserting it to the <body> element you will have a full colored cover of the page.
Example of setting a background color with the CSS background-color property:
You can also add a background color to specific elements in your document. For example, let’s see how to change the color of the heading and paragraphs.
Example of adding a background color to specific elements:
Let’s see another example, where we add a background color with a color name value to the <h1> element. We specify a RGB value for the <h2>, HSL for the <p>, and RGBa value for the <span> element.
Example of setting background colors with different color types:
Create a background with gradients
Gradient backgrounds let you create smooth transitions between two or more specified colors.
There are two types of gradient backgrounds: linear-gradient and radial-gradient.
In linear-gradient backgrounds, you can set a starting point for the colors. If you don’t mention a starting point, it will automatically set «top to bottom» by default.
Example of setting a linear-gradient background:
The given example shows a linear gradient that starts from the left. It starts from blue, transitioning to green. Change it according to your requirements.
In radial gradient backgrounds, the starting point is defined by its center.
Example of setting a radial-gradient background:
Create a changing background
You can create a background which will change its colors in the mentioned time. For that, add the animation property to the <body> element. Use the @keyframes rule to set the background colors through which you’ll flow, as well as the length of time each color will appear on the page.
How to Set background color in HTML?
A typical webpage consists of different elements. These can be submitted buttons, checkboxes, sign up or login buttons, a facility for smooth scrolling, a banner and carousel, and much more.
We use HTML properties and CSS to style all these elements. But even if all the elements look pretty, there needs to be a proper background for the page. This can be an image or just a color.
For this, you need to specify the color you want to the HTML style tag. Or, you might add your desired background color to the CSS stylesheet.
In this article, we will discuss the different aspects of setting the background color to the web page and its various elements.
Adding a background color to page body using the style attribute
You can set the background color to an HTML page body in two ways. You can use the bgcolor property within the body tag. The other method is by using the style attribute. In this process, the style attribute of the body tag is used. This style attribute has a background-color property, which you will use to set the background color of the web page.
The bgcolor property was used earlier, which is now removed from HTML 5.
Setting Background color of the body using bgcolor property (without using CSS):
Note: bgcolor property removed in HTML 5
Setting Background color of the body using style property (Inline CSS):
Output:
But you have to remember that the style attribute takes precedence over any other style specified for the web page. So, the properties mentioned suing the style attribute will override any style set in the <style> tag or a CSS style sheet.
Setting Background color of the body using CSS
Adding background color for HTML elements
We will now look at the different ways to add a background color to HTML elements:
Setting background color to Text
To set the required background color to the text on the page, you have to use the color property. You can specify the desired color in the <style> or mention it in the CSS sheet.
For example,
<p style=»color:red;»>I am red in color. </p> will work if you are not using a CSS stylesheet.
Otherwise, you can use the following code in CSS:
Setting background colour to a <table>, <td>, <th> Tags
Earlier, the bgcolor attribute was used for setting a color to a table. As it is depreciated in HTML 5, you will have to use CSS. For this, use the following CSS code:
The same property of background-color can be used for setting the color of table headers, rows, or cells in a table.
Output:
Setting background color to <div> tags
You can set the colors of your choice to the div and paragraph elements using HTML or CSS. In HTML, you can use the <style> tag. Use the following code:
Output:
Setting background color to form elements like button and textbox
Background color can be set to form elements such as button and textbox using the style tag in HTML. For example,
Output:
Setting background color to form elements like button and textbox using the ID attribute
If you are using CSS, you might set the color easily with the help of an id attribute. You can set the id value of a button or a textbox to anything you like. This id can then be referred to when writing CSS code. For example, if the button has and the textbox has the following CSS code will be applicable,
Setting background color to form elements like button and textbox using the class attribute
You can use class attribute the same as ID attribute, but the main difference between ID and the Class attribute is that we can use multiple class in any HTML element, but we have only one ID HTML element.
Different ways to define color in the background property
Using Hex color codes
You can specify the background color through hexadecimal color codes. You can mention this within the style tag or using the CSS background-color property.
This will set the background color to Indigo.
Using HTML color names
You can specify the color names in the HTML or CSS document for the web page or element background.
Using RGB color values
RGB values are used to define the amount of red, green, and blue using a number. This number lies between 0 and 255.
The RGB(255,0,0) value will make the background color red. This is because red is set to the highest amount, and the others are set to 0.
Using HSL color values
Another way to add background color is by using HSL values in HTML and CSS. It stands for hue, saturation, and lightness. Hue is the degree of intensity on the color wheel. Here, 0 means red, 240 is blue, and 120 is green. The saturation level is a percentage where 0 % is a shade of grey 100 % is the full color.
A percentage value is used for the lightness that defines the intensity of the color. Here, 0 % is black, and 100 % is white. 50 % is neither light nor dark. Use the code below for HSL values:
Create a Gradient Background
You can create a gradient background for a web page using CSS. There are two ways to go about it:
Background color linear gradient
In this method, the direction of the gradient is mentioned along with the colors. Directions such as to bottom, to top, to the right, to the left, or to the bottom right can be used.
For example,
You can also use multiple colors together. Instead of directions, you can use angles such as -90deg.
Output:
Background color radial gradient
Here, the gradient is defined by its center. You will have to mention at least two colors.
The basic syntax is as follows:
background-image: radial-gradient(shape size at position, start-color, . last-color);
For example,
Output:
Conclusion
The different ways to set background colors are discussed. You can either mention the styles within the HTML document using the <style> tag. You can also use external style sheets for setting the style properties. But make sure the values are correct when you are using hex codes and HSL values.
Как изменить цвет фона в HTML
Современные сайты часто используют в качестве фона страницы изображения (фотографии) или даже видео. И, тем не менее, знать простые способы изменения цвета фона страницы необходимо. Во всяком случае, обучение начинающих без этого не обходится.
Итак, если вы читали статью об обязательных тегах, то вы знаете, что текст страницы располагается между тегами <body></body>. Однако тег <body> не только определяет, где должен быть текст страницы, но и может задавать многие параметры, общие для всех элементов страницы.
Тег <body>
Слово body переводится с английского как “тело”. Всё, что находится между тегами <body></body> — это тело HTML-документа, это основа основ HTML-страницы.
В HTML4 (а также в XHTML) тег <body> может принимать множество атрибутов, управляющих цветом и фоном документа. Некоторые браузеры предоставляют дополнительные атрибуты для этого тега, однако мы не будем выходить за рамки стандарта HTML 4.
Всё, что находится между открывающим тегом <body> и закрывающим тегом </body> называется содержимым тела.
Закрывающий тег </body> в HTML можно не указывать, однако для совместимости с XHTML лучше все теги делать парными.
Атрибуты тега <body> условно можно разделить на три части:
- Атрибуты, которые управляют внешним видом документа.
- Атрибуты, которые связывают функции в сценариях с самим документом.
- Атрибуты, которые отмечают, то есть именуют, дают имя телу, чтобы на него можно было ссылаться из других элементов сайта.
На этом краткое знакомство с тегом <body> пока закончим, и перейдём к теме данной статьи.
Как задать цвет фона в HTML
Для задания цвета фона документа (страницы) используется атрибут bgcolor:
<body bgcolor=»red»>
В этом примере мы установили красный цвет фона страницы. Как задавать цвета с помощью имён и чисел, я уже рассказывал здесь.
В теге <body> можно задать цвет не только для фона, но и для текста страницы:
<body text=»yellow» bgcolor=»green»>
Здесь мы установили зелёный фон и жёлтый текст для страницы. При необходимости затем вы можете изменить цвет текста отдельного участка текста на странице, как это мы делали здесь.
Можно также задавать цвета и некоторых других элементов страницы (например, ссылок), но об этом в другой раз. Ну а если вам не терпится изучить все премудрости вёрстки сайтов прямо сейчас, то решение здесь.