Html box background image

CSS Multiple Backgrounds

In this chapter you will learn how to add multiple background images to one element.

You will also learn about the following properties:

CSS Multiple Backgrounds

CSS allows you to add multiple background images for an element, through the background-image property.

The different background images are separated by commas, and the images are stacked on top of each other, where the first image is closest to the viewer.

The following example has two background images, the first image is a flower (aligned to the bottom and right) and the second image is a paper background (aligned to the top-left corner):

Example

#example1 <
background-image: url(img_flwr.gif), url(paper.gif);
background-position: right bottom, left top;
background-repeat: no-repeat, repeat;
>

Multiple background images can be specified using either the individual background properties (as above) or the background shorthand property.

The following example uses the background shorthand property (same result as example above):

Example

CSS Background Size

The CSS background-size property allows you to specify the size of background images.

The size can be specified in lengths, percentages, or by using one of the two keywords: contain or cover.

The following example resizes a background image to much smaller than the original image (using pixels):

Lorem Ipsum Dolor

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Example

The two other possible values for background-size are contain and cover .

The contain keyword scales the background image to be as large as possible (but both its width and its height must fit inside the content area). As such, depending on the proportions of the background image and the background positioning area, there may be some areas of the background which are not covered by the background image.

The cover keyword scales the background image so that the content area is completely covered by the background image (both its width and height are equal to or exceed the content area). As such, some parts of the background image may not be visible in the background positioning area.

The following example illustrates the use of contain and cover :

Example

#div1 <
background: url(img_flower.jpg);
background-size: contain;
background-repeat: no-repeat;
>

#div2 background: url(img_flower.jpg);
background-size: cover;
background-repeat: no-repeat;
>

Define Sizes of Multiple Background Images

The background-size property also accepts multiple values for background size (using a comma-separated list), when working with multiple backgrounds.

The following example has three background images specified, with different background-size value for each image:

Example

#example1 <
background: url(img_tree.gif) left top no-repeat, url(img_flwr.gif) right bottom no-repeat, url(paper.gif) left top repeat;
background-size: 50px, 130px, auto;
>

Full Size Background Image

Now we want to have a background image on a website that covers the entire browser window at all times.

The requirements are as follows:

  • Fill the entire page with the image (no white space)
  • Scale image as needed
  • Center image on page
  • Do not cause scrollbars

The following example shows how to do it; Use the element (the element is always at least the height of the browser window). Then set a fixed and centered background on it. Then adjust its size with the background-size property:

Example

Hero Image

You could also use different background properties on a to create a hero image (a large image with text), and place it where you want.

Example

.hero-image <
background: url(img_man.jpg) no-repeat center;
background-size: cover;
height: 500px;
position: relative;
>

CSS background-origin Property

The CSS background-origin property specifies where the background image is positioned.

The property takes three different values:

  • border-box — the background image starts from the upper left corner of the border
  • padding-box — (default) the background image starts from the upper left corner of the padding edge
  • content-box — the background image starts from the upper left corner of the content

The following example illustrates the background-origin property:

Example

#example1 <
border: 10px solid black;
padding: 35px;
background: url(img_flwr.gif);
background-repeat: no-repeat;
background-origin: content-box;
>

CSS background-clip Property

The CSS background-clip property specifies the painting area of the background.

The property takes three different values:

  • border-box — (default) the background is painted to the outside edge of the border
  • padding-box — the background is painted to the outside edge of the padding
  • content-box — the background is painted within the content box

The following example illustrates the background-clip property:

Example

#example1 <
border: 10px dotted black;
padding: 35px;
background: yellow;
background-clip: content-box;
>

CSS Advanced Background Properties

Property Description
background A shorthand property for setting all the background properties in one declaration
background-clip Specifies the painting area of the background
background-image Specifies one or more background images for an element
background-origin Specifies where the background image(s) is/are positioned
background-size Specifies the size of the background image(s)

Источник

background-image

The background-image CSS property sets one or more background images on an element.

Try it

The background images are drawn on stacking context layers on top of each other. The first layer specified is drawn as if it is closest to the user.

The borders of the element are then drawn on top of them, and the background-color is drawn beneath them. How the images are drawn relative to the box and its borders is defined by the background-clip and background-origin CSS properties.

If a specified image cannot be drawn (for example, when the file denoted by the specified URI cannot be loaded), browsers handle it as they would a none value.

Note: Even if the images are opaque and the color won’t be displayed in normal circumstances, web developers should always specify a background-color . If the images cannot be loaded—for instance, when the network is down—the background color will be used as a fallback.

Syntax

Each background image is specified either as the keyword none or as an value.

To specify multiple background images, supply multiple values, separated by a comma:

background-image: linear-gradient( to bottom, rgba(255, 255, 0, 0.5), rgba(0, 0, 255, 0.5) ), url("catfront.png"); /* Global values */ background-image: inherit; background-image: initial; background-image: revert; background-image: revert-layer; background-image: unset; 

Values

Is a keyword denoting the absence of images.

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

Initial value none
Applies to all elements. It also applies to ::first-letter and ::first-line .
Inherited no
Computed value as specified, but with url() values made absolute
Animation type discrete

Formal syntax

Examples

Layering background images

Note that the star image is partially transparent and is layered over the cat image.

HTML

div> p class="catsandstars">This paragraph is full of catsbr />and stars.p> p>This paragraph is not.p> p class="catsandstars">Here are more cats for you.br />Look at them!p> p>And no more.p> div> 

CSS

p  font-size: 1.5em; color: #fe7f88; background-image: none; background-color: transparent; > div  background-image: url("mdn_logo_only_color.png"); > .catsandstars  background-image: url("startransparent.gif"), url("catfront.png"); background-color: transparent; > 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

  • Implementing image sprites in CSS
  • Image-related data types: ,
  • Image-related functions:
    • cross-fade()
    • element()
    • image()
    • image-set()
    • linear-gradient()
    • radial-gradient()
    • conic-gradient()
    • repeating-linear-gradient()
    • repeating-radial-gradient()
    • repeating-conic-gradient()
    • paint()
    • url()

    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.

    Источник

    Как добавить изображение фоном. Свойство background-image

    background-image позволяет добавить изображение в качестве фона для выбранного элемента. Фоновое изображение может быть любого типа и повторяться или масштабироваться в зависимости от настроек.

    Значения

    • url(‘путь_к_изображению’) — указывает путь к изображению. Вы можете указать относительный путь к изображению на вашем сервере или абсолютный URL для изображения в интернете.
    • none — значение по умолчанию, где нет фона. Если не хотите использовать изображение в качестве фона, вы можете установить background-image: none; .
    • linear-gradient() , radial-gradient() , repeating-linear-gradient() , repeating-radial-gradient() — создают градиент фона без использования изображений. Можно определить цветовую палитру и ориентацию градиента.

    Повторное изображение

    background-repeat: repeat; — значение по умолчанию, изображение повторяется по горизонтали и вертикали. Изображение будет заполнять фон элемента, повторяясь при необходимости.

    background-repeat: repeat-x; — повторяется только по горизонтали.

    background-repeat: repeat-y; — повторяется только по вертикали.

    background-repeat: no-repeat; — отображается только один раз без повторения.

    Размер изображения

    background-size: auto; — отображается в своём естественном размере.

    background-size: cover; — масштабируется так, чтобы полностью заполнить фон элемента, возможно, обрезая его.

    background-size: contain; — масштабируется так, чтобы полностью поместиться в фон элемента без искажений. Белые полосы могут появиться по краям фона, если пропорции изображения и фона не совпадают.

    Наследование

    Свойство background-image не наследуется дочерними элементами. Каждый элемент должен самостоятельно задавать фоновое изображение.

    Примеры использования

    Добавление изображения на фон определённого элемента

    Добавление повторяющегося изображения на фон элемента

    Добавление градиента на фон

    Нюансы использования

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

    ⭐ Поддержка браузерами свойства background-image

    Материалы по теме

    «Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.

    Источник

    Читайте также:  Java scripts for site
Оцените статью