Background image img src css

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

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; 

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.

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
Читайте также:  Кнопка сохранить pdf html

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 20, 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.

    Источник

    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.

    CSS Syntax

    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:

    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:

    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%);
    >

    Источник

    Как сделать картинку фоном в HTML и CSS. 3 простых способа

    Приветствую. В этой статье я хочу рассказать о трех способах размещения изображения в качестве фона всей страницы при помощи только HTML + CSS (без использования JS).

    Итак, требования к фоновому изображению у нас следующие:

    • Покрывается 100% ширины и высоты страницы
    • Фон масштабируется при необходимости (background растягивается или сжимается в зависимости от размеров экрана)
    • Сохраняются пропорции картинки (aspect ratio)
    • Изображение центрировано на странице
    • Фон не вызывает скроллов
    • Решение максимально кроссбраузерное
    • Не используются никакие другие технологии кроме CSS

    design-development-electronics-326424.jpg

    Способ 1

    На мой взгляд, это лучший способ, ведь он самый простой, лаконичный и современный. Он использует свойство CSS3 background-size , которое мы применяем к тегу html . Именно html , а не body , т.к. его высота больше или равна высоте окна браузера.

    Устанавливаем фиксированный и центрированный фон, затем корректируем его размер, используя background-size: cover .

    Chrome (любая версия) Opera 10+ Firefox 3.6+ Safari 3+ IE 9+

    Для того чтобы изображения загружались быстро, размещайте свои сайты только у проверенных хостинг-провайдеров, например, Beget.com Пользователи и поисковые системы любят быстрые сайты.

    Способ 2

    Этот способ предусматривает использование элемента img, размер которого будет изменяться в зависимости от размера окна браузера. Чтобы растянуть изображение на весь экран, ему необходимо задать min-height и width со значением 100%. А чтобы изображение не сжималось до размера меньшего, чем оригинальный, установим min-width со значением равным ширине картинки.

    В случае если ширина окна будет меньше ширины изображения, будет использоваться media query для выравнивания бэкграунда по центру.

    Способ 3

    Еще один способ заключается в следующем: фиксируем изображение к левому верхнему углу страницы и растягиваем его при помощи свойств min-width и min-height 100%, сохраняя при этом соотношение сторон.

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

    Этот способ работает в хороших браузерах и IE 8+.

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

    Источник

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