Анимированный фон

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.

Читайте также:  Php include at runtime

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.

    Источник

    How to Set GIF as a Background Image on the Webpage?

    Setting the GIF “Graphics Interchange Format” as a background image adds a visually appealing element to the design. GIF allows developers to convey information or highlight a product or service which helps in creating a brand’s visual identity. However, the developers must ensure that the usage of GIFs does not overwhelm the webpage or distract the user from the main content.

    This article demonstrates the procedure of setting a GIF as a background image on the webpage.

    How to Set GIF as a Background Image on the Webpage?

    Setting a GIF as a background image helps in creating eye-catching elements by adding visual elements.

    GIFs are particularly useful on websites that want to convey a sense of playfulness or whimsy, or on pages that want to highlight a particular product or feature. For setting it, as a background image visit the following examples:

    Example 1: Setting GIF as a Fixed Background

    As the HTML elements that help in building the content of the webpage are placed inside the “ ” tag. That is why, selecting the “body” element and applying CSS properties on it. It affects all the containing HTML elements of the “ ” tag.

    For instance, the “ ” and “ ” tags are utilized as the content of the webpage. See the below code snippet:

    < body >
    < h1 >Setting GIF as a Background Image On The Page
    < p >This GIF has been added as a background image on the whole page using «background-image» Property. This Article has been powered by Linuxhint.


    Now, select the “body” HTML element inside the “ ” tag or in a separate “CSS” file to apply styling on the webpage:

    body {
    background-image: url ( ‘sea.gif’ ) ;
    background-repeat: no-repeat;
    background-size: cover;
    padding:50px;
    font-size: x-large;
    color: white;
    }

      • First, the “url()” method is utilized which stores the path of the “GIF” file. And this method is passed as a value to the CSS “background-image” property.
      • Next, set “no-repeat” as a value to the CSS “background-repeat” property for the repetition of the GIF file.
      • Then, set the value of “cover” to the CSS “background-size” property to cover all the available space
      • After that, provide the value of “50px” and “x-large” to the CSS “padding” and “font-size” properties, respectively. This adds spacing around the text and magnifies the font size.

      After the compilation, the webpage looks like this:

      The above output shows that a gif has been added as a background on the webpage.

      Example 2: Setting GIF as a Scrollable Background

      Initially, create an HTML structure to make a Webpage content like this:

      < div class = "contai" >
      < h1 >Setting GIF as a Background Image On The Page
      < p >This GIF has been added as a background image on the whole page using the «background-image» Property. This Article has been powered by Linuxhint.


    • First, the parent “ ” tag is utilized with a class of “contai”.
    • Next, use “h1” and “p” HTML elements and provide dummy content to them.
    • After that, create another “ ” and utilize the “ ” tag by providing dummy data to it.

    Now, add GIF as a background on the web page by inserting the following CSS properties:

    .contai {
    background-image: url ( sea.gif ‘);
    background-repeat: no-repeat;
    background-size: cover;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    color: white;
    font-size: large;
    text-align: center;
    padding: 2rem;
    >

    The description of the above-used code block:

      • First, set the “image-path”, “no-repeat” and “cover” as a value to the CSS “background-image”, “background-repeat” and “background-size” properties, respectively.
      • Next, set the value of “100vh” and “flex” to the CSS “height” and “display” properties.
      • After that, utilize the CSS “color”, “font-size”, “text-align” and “padding” properties to apply styling to the content.

      After the end of the compilation process, the webpage looks like this:

      The output displays that the “GIF” has been inserted as a background image on the whole page.

      Conclusion

      To set GIF as a background image on the webpage, the CSS “background-image” property is utilized on the HTML “body” element. The CSS property that is applied to the “body” element is automatically applied to all containing elements. By setting the “100vh” as a value to the height property, the scrolling effect can also be enabled. It allows the background gif to move along the scroll. This article has demonstrated how to set a GIF as a background image on the webpage.

      About the author

      Abdul Moeed

      I’m a versatile technical author who thrives on adaptive problem-solving. I have a talent for breaking down complex concepts into understandable terms and enjoy sharing my knowledge and experience with readers of all levels. I’m always eager to help others expand their understanding of technology.

      Источник

      Можно ли сделать анимированный фон?

      Мультипликация это достаточно сильный прием, способный оживить любой документ, поэтому не удивительно, что огромную популярность приобрела технология Flash, которая добавляет на веб-страницы мультики, к тому же интерактивные. Графический формат GIF также поддерживает простейшую анимацию путем последовательной смены кадров. Так что используя изображение в этом формате допустимо анимировать не только отдельные картинки, но также фон веб-страницы или определенного элемента.

      Вначале потребуется создать анимированную картинку в формате GIF, для чего можно воспользоваться программой Adobe Photoshop или другой подходящей для этой цели. Также существуют библиотеки готовых анимированных файлов, которые можно применять в качестве фоновой картинки. Далее изображение добавляется в качестве фона с помощью стилевого свойства background , как показано в примере 1.

      Пример 1. Анимированный фон веб-страницы

      HTML5 CSS 2.1 IE Cr Op Sa Fx

             

      Содержимое веб-страницы

      В данном примере файл light.gif устанавливается в качестве фоновой картинки в правом нижнем углу веб-страницы. Также задается черный цвет фона.

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

      Источник

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

      Источник

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