Как вставить background image в css
Перейти к содержимому

Как вставить background image в css

  • автор:

Background-image: установка фонового изображения

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

Как видим, фотографии и иллюстрации позволяют сделать дизайн уникальным, выделить его среди других, сделать запоминающимся и ярким.

В данном уроке мы познакомим вас с одним из нескольких свойств, отвечающих за настройку фона в CSS — это свойство background-image . В следующих уроках мы рассмотрим остальные свойства, а также сокращенную запись background.

Возможности свойства CSS background-image

Свойство background-image устанавливает выбранное изображение в качестве фона элемента. В зависимости от цели, можно задать графический фон как для отдельного блока, так и для всей страницы. В качестве единственного значения принимается URL-адрес графического файла. Запись выглядит так:

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

CSS Background Image

The background-image property specifies an image to use as the background of an element.

By default, the image is repeated so it covers the entire element.

Example

Set the background image for a page:

body <
background-image: url(«paper.gif»);
>

Example

This example shows a bad combination of text and background image. The text is hardly readable:

body <
background-image: url(«bgdesert.jpg»);
>

Note: When using a background image, use an image that does not disturb the text.

The background image can also be set for specific elements, like the

element:

Example

p <
background-image: url(«paper.gif»);
>

The CSS Background Image Property

Property Description
background-image Sets the background image for an element

Get Certified

COLOR PICKER

colorpicker

Get your server with W3Schools Spaces

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

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:

  • background-size
  • background-origin
  • background-clip

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

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

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.

Here is the code:

Example

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

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

html <
background: url(img_man.jpg) no-repeat center fixed;
background-size: cover;
>

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)

CSS background-image Property

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

By default, a background-image is placed at the top-left corner of an element, and repeated both vertically and horizontally.

Tip: The background of an element is the total size of the element, including padding and border (but not the margin).

Tip: Always set a background-color to be used if the image is unavailable.

Default value: none
Inherited: no
Animatable: no. Read about animatable
Version: CSS1 + new values in CSS3
JavaScript syntax: object.style.backgroundImage=»url(img_tree.gif)» Try it

Browser Support

The numbers in the table specify the first browser version that fully supports the property.

Property
background-image 1.0 4.0 1.0 1.0 3.5

CSS Syntax

background-image: url|none|initial|inherit;

Property Values

Value Description Demo
url(‘URL‘) The URL to the image. To specify more than one image, separate the URLs with a comma Demo ❯
none No background image will be displayed. This is default
conic-gradient() Sets a conic gradient as the background image. Define at least two colors Demo ❯
linear-gradient() Sets a linear gradient as the background image. Define at least two colors (top to bottom) Demo ❯
radial-gradient() Sets a radial gradient as the background image. Define at least two colors (center to edges) Demo ❯
repeating-conic-gradient() Repeats a conic gradient Demo ❯
repeating-linear-gradient() Repeats a linear gradient Demo ❯
repeating-radial-gradient() Repeats a radial gradient Demo ❯
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

More Examples

Example

Sets two background images for the element. Let the first image appear only once (with no-repeat), and let the second image be repeated:

body <
background-image: url(«img_tree.gif»), url(«paper.gif»);
background-repeat: no-repeat, repeat;
background-color: #cccccc;
>

Example

Use different background properties to create a «hero» image:

.hero-image <
background-image: url(«photographer.jpg»); /* The image used */
background-color: #cccccc; /* Used if the image is unavailable */
height: 500px; /* You must set a specified height */
background-position: center; /* Center the image */
background-repeat: no-repeat; /* Do not repeat the image */
background-size: cover; /* Resize the background image to cover the entire container */
>

Example

Sets a linear-gradient (two colors) as a background image for a element:

#grad1 <
height: 200px;
background-color: #cccccc;
background-image: linear-gradient(red, yellow);
>

Example

Sets a linear-gradient (three colors) as a background image for a element:

#grad1 <
height: 200px;
background-color: #cccccc;
background-image: linear-gradient(red, yellow, green);
>

Example

The repeating-linear-gradient() function is used to repeat linear gradients:

#grad1 <
height: 200px;
background-color: #cccccc;
background-image: repeating-linear-gradient(red, yellow 10%, green 20%);
>

Example

Sets a radial-gradient (two colors) as a background image for a element:

#grad1 <
height: 200px;
background-color: #cccccc;
background-image: radial-gradient(red, yellow);
>

Example

Sets a radial-gradient (three colors) as a background image for a element:

#grad1 <
height: 200px;
background-color: #cccccc;
background-image: radial-gradient(red, yellow, green);
>

Example

The repeating-radial-gradient() function is used to repeat radial gradients:

#grad1 <
height: 200px;
background-color: #cccccc;
background-image: repeating-radial-gradient(red, yellow 10%, green 20%);
>

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *