Тег BODY, атрибут background

Атрибут background

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

Синтаксис

Значения

Любой допустимый адрес изображения — можно использовать относительный или абсолютный путь.

Значение по умолчанию

Аналог CSS

Валидация

Использование этого атрибута осуждается спецификацией HTML, валидный код получается только при использовании переходного .

     . 

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

Читайте также:  Simple problem in java

Типы тегов

HTML5

Блочные элементы

Строчные элементы

Универсальные элементы

Нестандартные теги

Осуждаемые теги

Видео

Документ

Звук

Изображения

Объекты

Скрипты

Списки

Ссылки

Таблицы

Текст

Форматирование

Формы

Фреймы

Источник

Атрибут background

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

Синтаксис

Значения

Любой допустимый адрес изображения — можно использовать относительный или абсолютный путь.

Значение по умолчанию

Аналог CSS

Валидация

Использование этого атрибута осуждается спецификацией HTML, валидный код получается только при использовании переходного .

     . 

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

Типы тегов

HTML5

Блочные элементы

Строчные элементы

Универсальные элементы

Нестандартные теги

Осуждаемые теги

Видео

Документ

Звук

Изображения

Объекты

Скрипты

Списки

Ссылки

Таблицы

Текст

Форматирование

Формы

Фреймы

Источник

HTML Background Images

A background image can be specified for almost any HTML element.

Background Image on a HTML element

To add a background image on an HTML element, use the HTML style attribute and the CSS background-image property:

Example

Add a background image on a HTML element:

You can also specify the background image in the element, in the section:

Example

Specify the background image in the element:

Background Image on a Page

If you want the entire page to have a background image, you must specify the background image on the element:

Example

Add a background image for the entire page:

Background Repeat

If the background image is smaller than the element, the image will repeat itself, horizontally and vertically, until it reaches the end of the element:

Example

To avoid the background image from repeating itself, set the background-repeat property to no-repeat .

Example

Background Cover

If you want the background image to cover the entire element, you can set the background-size property to cover.

Also, to make sure the entire element is always covered, set the background-attachment property to fixed:

This way, the background image will cover the entire element, with no stretching (the image will keep its original proportions):

Example

Background Stretch

If you want the background image to stretch to fit the entire element, you can set the background-size property to 100% 100% :

Try resizing the browser window, and you will see that the image will stretch, but always cover the entire element.

Example

Learn More CSS

From the examples above you have learned that background images can be styled by using the CSS background properties.

To learn more about CSS background properties, study our CSS Background Tutorial.

Источник

background

The background shorthand CSS property sets all background style properties at once, such as color, image, origin and size, or repeat method. Component properties not set in the background shorthand property value declaration are set to their default values.

Try it

Constituent properties

This property is a shorthand for the following CSS properties:

Syntax

/* Using a */ background: green; /* Using a and */ background: url("test.jpg") repeat-y; /* Using a and */ background: border-box red; /* A single image, centered and scaled */ background: no-repeat center/80% url("../img/image.png"); /* Global values */ background: inherit; background: initial; background: revert; background: revert-layer; background: unset; 

The background property is specified as one or more background layers, separated by commas.

The syntax of each layer is as follows:

  • Each layer may include zero or one occurrences of any of the following values:
    • The value may only be included immediately after , separated with the ‘/’ character, like this: » center/80% «.
    • The value may be included zero, one, or two times. If included once, it sets both background-origin and background-clip . If it is included twice, the first occurrence sets background-origin , and the second sets background-clip .
    • The value may only be included in the last layer specified.

    Values

    See background-clip and background-origin . Default: border-box and padding-box respectively.

    See background-color . Default: transparent .

    The following three lines of CSS are equivalent:

    background: none; background: transparent; background: repeat scroll 0% 0% / auto padding-box border-box none transparent; 

    Accessibility concerns

    Browsers do not provide any special information on background images to assistive technology. This is important primarily for screen readers, as a screen reader will not announce its presence and therefore convey nothing to its users. If the image contains information critical to understanding the page’s overall purpose, it is better to describe it semantically in the document.

    Formal definition

    • background-image : none
    • background-position : 0% 0%
    • background-size : auto auto
    • background-repeat : repeat
    • background-origin : padding-box
    • background-clip : border-box
    • background-attachment : scroll
    • background-color : transparent
    • background-position : refer to the size of the background positioning area minus size of background image; size refers to the width for horizontal offsets and to the height for vertical offsets
    • background-size : relative to the background positioning area
    • background-image : as specified, but with url() values made absolute
    • background-position : as each of the properties of the shorthand:
      • background-position-x : A list, each item consisting of: an offset given as a combination of an absolute length and a percentage, plus an origin keyword
      • background-position-y : A list, each item consisting of: an offset given as a combination of an absolute length and a percentage, plus an origin keyword
      • background-color : a color
      • background-image : discrete
      • background-clip : a repeatable list of
      • background-position : a repeatable list of
      • background-size : a repeatable list of
      • background-repeat : discrete
      • background-attachment : discrete

      Formal syntax

      background =
      [ # , ]?

      =
      ||
      [ / ]? ||
      ||
      ||
      ||

      =
      ||
      ||
      [ / ]? ||
      ||
      ||
      ||

      =
      |
      none

      =
      [ left | center | right | top | bottom | ] |
      [ left | center | right | ] [ top | center | bottom | ] |
      [ center | [ left | right ] ? ] && [ center | [ top | bottom ] ? ]

      =
      [ | auto ] |
      cover |
      contain

      =
      repeat-x |
      repeat-y |
      [ repeat | space | round | no-repeat ]

      =
      scroll |
      fixed |
      local

      =
      border-box |
      padding-box |
      content-box

      =
      |

      =
      |

      =
      url( * ) |
      src( * )

      Examples

      Setting backgrounds with color keywords and images

      HTML

      p class="topbanner"> Starry skybr /> Twinkle twinklebr /> Starry sky p> p class="warning">Here is a paragraphp> p>p> 

      CSS

      .warning  background: pink; > .topbanner  background: url("starsolid.gif") #99f repeat-y fixed; > 

      Result

      Specifications

      Browser compatibility

      BCD tables only load in the browser

      See also

      Found a content problem with this page?

      This page was last modified on Jul 18, 2023 by MDN contributors.

      Your blueprint for a better internet.

      MDN

      Support

      Our communities

      Developers

      Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
      Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

      Источник

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