Как установить анимацию на фоне?
В последнее время стало очень популярным добавление небольшой анимации на сайт. Это придает эффект реальности в некотором плане. Вследствие этого все чаще и чаще слышишь про программу Flash. С ее помощью можно создавать интерактивные анимации, которые в дальнейшем вставляются на сайт. Существует также более старый способ, который в последнее время стал очень популярным в социальных сетях. Речь идет о изображениях в формате .gif, которые обладают способностью последовательно менять кадры. Благодаря этому можно создать анимацию.
Чтобы создать свою анимацию, которая попадет на сайт, не требуется большого ума или сверхспособностей. В первую очередь нужен графический редактор. Вполне подойдет один из самых популярных — Adobe Photoshop. В этой среде создается анимированная картинка. Кроме этого существует много сайтов с целыми библиотеками готовых анимашек, если тебе лень создавать свой документ, можешь порыться в интернете и найти достойную анимацию. А после этого все просто элементарно, работаем в том же режиме, когда нам нужно установить обычную фоновую картинку, то есть обращаемся к свойству background, как это показано в примере
На заметку
При использовании анимации следует помнить, что они привлекают к себе внимание. В одних случаях это может сыграть вам на руку, а в других — помешать. К примеру, когда анимация будет отвлекать пользователя от изучения основной информации сайта.
Как сделать анимированный фон на странице

Пару дней назад мне задали вопрос по поводу того, как сделать анимированный фон на странице. При этом человек знал и про background, и про CSS. Он у меня попросил скрипт на JavaScript, позволяющий делать анимацию фона. Я ему сказал, что здесь JavaScript совсем не нужен. И показал ему, как можно сделать анимированный фон только с применением CSS. Вот об этом способе я и напишу в данной статье.
Способ совершенно тривиальный и простой, думаю, что многие до него додумаются сразу. Вот CSS-код:
html <
background: url(images/bg.gif) no-repeat; /* Задаём фон GIF-картинкой */
height: 100%; /* 100% высота страницы */
>
Ключевым моментом здесь является GIF-изображение. Думаю, что Вам известно, что в GIF можно делать достаточно сложную анимацию (в рамках целесообразности, конечно). Поэтому никаких скриптов не нужно, чтобы сделать любой фон, а не только страницы, анимированным.
Таким образом, достаточно создать анимированный GIF, вставить его на страницу самым простым CSS-кодом, и у Вас получится анимированный фон на странице.

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
Она выглядит вот так:
Комментарии ( 19 ):
Совсем просто интересно зачем задавали такой вопрос
Не нашел где спросить, спрошу тут) У меня есть сайт свой, могу показать если попросите, так вот, когда я его открываю через телефон (iphone), то он открывает его не весь, а часть где-то 80%, когда все остальные сайты открываются на 100% такая же фигня и в яндекс баре (закладки) там окошки с сайтами, так же на окошке этом сайт виден на 80% а все остальные вмещает на 100%. Сравнивал CSS коды, разницы существенной не заметил, Помогите пожалуйста) Как то туфтово все описал, думаю Вы поймете)
Дело в вёрстке, точнее в её низком качестве. Ничего сказать невозможно, кроме как посоветовать научиться хорошо верстать и всё сделать заново. Вот курс по вёрстке: http://srs.myrusakov.ru/makeup
Михаил! Помогите! У меня на сайте есть шапка и на шапке кнопки! Если смотреть на сайте при масштабе 100% то всё нормально, но если смотреть на 50% или 200% и т.п. Шапка и кнопки сдвигаются! А на вашем сайте только масштаб уменьшается, а кнопки остаются на местах! Как вы это сделалил напишите пожалуйста.
Используйте относительные размеры (то есть проценты), тогда они будут изменяться в зависимости от масштаба.
Я пробовал! Но если я ставлю width = 100%; То у меня появляются отступы слева и справо! Тоже самое и с высотой! Что делать?
Отступы слева и справа — это margin (или padding). Вряд ли они у изображения, возможно, они у body. Поэтому поставьте у body
У меня шапка залита в <head>. Поставить это в head. Или перенести шапку в body?
В <head> вообще не должно быть контента. Весь контент в <body>.
перенесу шапку в body и сделаю как вы писали! Спасибо
Шапку сделал как вы сказали! Всё нормально! А вот у меня прямо на шапке есть кнопки навигации! Как с ними быть? Потому что если я меняю масштаб то шапка остаётся как было, а кнопки сдвигаются кто куда! Попробовал расставить кнопки на шапке с помощью % , а не px! Но это не помогло!
Значит проблема в Вашей верстке. Что именно происходит с кнопками?
У меня сделаны анимированные кнопки по вашему уроку http://myrusakov.ru/css-hover-image.html Ну вот когда я меняю масштаб в браузере то кнопки(которые сделаны на картинке-шапке) Начинают "Прыгать"! Сбивается их положение! Если они были до этого на шапке то они выходят за её пределы и т.п.
Они так и должны прыгать. Иначе придется ставить фиксированное position. Задавать left, top и так далее.
Нужно position: absolute; и свойства left, top, right и bottom. И ещё margin-top, а не margin top.
Всё равно что-то не получается!:( вот код: .but < top: 220px; position: absolute; right:100px; bottom:290px; left: 500px; >И тем не менее они всё равно смещаются
Всё! Вроде разобрался! Заместо position: absolute ПОСТАВИЛ: position: static (что в прочем и так по умолчанию стоит!) И всё стало норм!:)
У меня почему-то не получилось задать фон таким способом.
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.
33 Animated Backgrounds Examples [With Pure CSS]
You can use a CSS background animation to help your site stand out from the crowd, emphasize your branding, or simply look awesome. And because CSS has gotten so powerful, you can create some great-looking CSS background effects without needing a single line of JavaScript. Now you can even create a video background just with CSS!! Who would have told us that 15 years ago, huh?
So, here are 20 great animated backgrounds you can use in your projects, or draw inspiration from! Ideal for hero slider websites.
1) Animated Background Colours in CSS
Let’s start with the basics. A simple color fades — you can use @keyframes to fade the background between as many colors as you need and use the percentages to determine how long the animation will stay on that color before changing.
Simple, easy to implement, and effective.
2) CSS Animated Background Gradient
Now let’s take it up a notch — instead of a single color fading into another, you can add an extra touch of class with a gradient, pleasantly sweeping back and forth across the screen. This is one of the easiest ways to make a moving background in CSS.
3) Floating Squares
Time to add some objects into the mix! Here’s a cool moving background (CSS only, believe it or not) by TokyoWeb. These semi-transparent rotating squares float up the screen.
This looks cool as-is, but the cool thing is, you can play around with the code to create different colors, shapes, directions, and speeds. Put your creative hat on and see what you come up with.
4) SVG Animation (HTML Animated Background)
If you are not familiar with SVG this animation will look like magic to you. There’s not a single line of CSS or JS. It’s done purely using HTML. A pure HTML animated background.
This is one of the coolest HTML background animations I’ve ever seen. It gives me the same vibes as some old Mac OS X screensavers with those sophisticated gradients that never get old and gives a super modern look.
5) Animated Moving Squares Background
If you are looking for a subtle yet modern animation, this animated background made of squares can be the ideal candidate for your page.
This animation is purely made on CSS and the effect can easily be applied to almost any website because due to its nondistracting nature. You can apply this animated background to your whole website or specific sections of your site.
6) Basic Landscape Background Animation
This example showcases one of the most basic background animations by animating the position of an image from left to right.
However, when done with the right picture like in this example, it shows the potential that it can have for a landing page.
7) Grid Background Animation
This animation is not only made with pure CSS but also with cero HTML!
It uses the CSS keyframes feature to animate the background position of a grid background. The effect has been applied to the body of the page and can be applied to any other element too.
8) Animated Background of Figures
This animation gives your site a trendy vibe. It animates some basic figures up and down with some easing effects giving your background a new touch.
The figures are made out of base64 images and the background animation is done by using CSS keyframes and CSS transformations. All very basic stuff.
9) Text Background Animation
Although it seems can be considered a text animation at first glance, this animation is technically a background animation within a text element.
It creates a very interesting effect and it can be quite a nice visual effect when choosing the right background and a thick font.
10) Blob Background Animation
Yes, it is possible to have a blob animation without using JavaScript, and here’s an example to prove it.
Using the CSS border-radius property we can create a blob element then we can then rotate as usual by using the CSS transform property. Now you can add animated blobs to your websites!
11) Circle Backgrounds
Another subtle animation that you can add to your page to automatically give it a modern look without much effort.
The animation is very basic but the effect it creates looks so cool! The effect is done by animating each individual circle with a different pulse effect using the CSS keyframe property.
12) Particles Animation
Here’s another example that shows us how to animate glowing particles using CSS and HTML elements.
You can apply this effect as a background although is not really a background animation per se.
13) Scroll Background Animation
Another example of a super basic animation is that when used appropriately can give your site a totally new look.
It uses a basic vertical animation using mimicking the scrolling of a blurred website in the background. It uses CSS keyframes and transform to perform the movement of the background image.
14) Wave Background Animation
Wave animations are actually a thing. In fact, waves were actually a thing even before having them animating in the background.
Here is one of the best wave CSS animations you can use for your background. It uses multiple layers of waves and adds the parallax effect and opacity to give it a sense of depth.
15) Fireworks CSS background effects — version 1
This pure CSS animated firework effect would look great by itself (could be cool on a "Congratulations" or "Success" page or something like that), but could look even cooler with a foreground image, maybe a cityscape.
16) Fireworks CSS background effects — version 2
Here’s another approach you could take to fireworks — this version has a different feel — the particles have a more natural movement, almost as if there’s a gravity to them.
17) Seeding CSS background effect
This moving background (using only CSS) feels a bit like moving through a ball pool at warp speed. I like it.
18) Blurred Lines
If Robin Thicke made CSS background effects, this might be the sort of thing he came up with. This one is eye-catching without being distracting — notice that even with this quite light typeface, the text is still easy to read.
19) Retro Grid Animated CSS background
Are you a fan of the 80s retro look? Are you building a site for a synthwave artist? Or can you simply not let go of the past? If the answer to any of these questions is "Yes", then you’ll love this excellent Tron-style retro grid animation!
You can change the colors with the variables $computationalFogBot setting the background, and $nodeStreak setting the color of the bars.
For another example of this theme, check out this one, too:
20) Snowfall Effect Animated Background (CSS only)
I don’t know whether it’s the festive season at the time you’re reading this. For me, it doesn’t matter. I’ll put my Santa hat on and watch Elf any time of year. If you feel the same, then here’s a nice snowfall effect for you — with actual snowflakes!
21) Parallax Snowfall Background
What’s that you say, you want even more snow? OK. How about this one then? This has much heavier snowfall, and a very nice parallax effect to boot.
22) Infinite triangles
This one plays tricks with your brain. Are the triangles moving up or down? Expanding or contracting? No one knows — that’s fun.
23) Floating Heart Infinite Animation
Much like the triangles above, here’s another CSS background animation that falls squarely into the "trippy" category. With this one, not only do you get a cool background animation, but you get to open your chakras at the same time. Bonus.
24) CSS Fireflies
These little fireflies invoke a sense of wonder and intrigue. The effect looks cool with the forest background, but works well on just a plain color, too:
25) Hypno-Squares
These Hypno squares are cute and pretty unique. Don’t look at them too long though — they might be transmitting subliminal messages to your subconscious mind.
26) Blurry Bubbles Animation
These blurred/slightly out-of-focus bubbles pop into existence seemingly at random, bring delight and happiness for a short time, and then slowly but inevitably fade away. Which, incidentally, is also an accurate description of my love life — but that’s a story for another time.
27) CSS Animated Lava Lamp
OK, so far you’ve seen some cool CSS background animation examples which you can pretty much plug and play. Now let’s explore what’s possible when you’re at the top of your game — starting with this CSS-only lava lamp by Janos Szudi!
28) Matrix Effect Animated Background (CSS)
This is nice. The whole thing is done just through color changes on the little square elements, creating an instantly recognizable effect.

29) Lighthouse at night CSS background animation
How about this amazing piece of work by Cameron Fitzwilliam! Now, this one does use JS. but. the JS just controls the way the image reacts to your mouse movement. You can delete all the JS and the animations on the wave and the lighthouse light will still work. So I’m allowing it.
30) Single Div Pure CSS Book Search
This is a really nice and cute CSS animation by the awesome Lynn Fisher. But check out the HTML box in the editor. No, don’t adjust your monitor, you are seeing that right — she made this using a single div. Pure CSS doesn’t get any purer than that! Or does it.
31) Diagonal Lines Animation
This animation won’t require you to write a single line of HTML, it’s all done in CSS alone.
The lines on the background are created using the repeating-linear-gradient property and then animated as usual by using and keyframes animation.
32) Snow Background
Ideal to use for the Christmas season to give your page a new design.
This animation uses parallax animation to animate at different speeds the different layers of snowballs. This way it creates a more realistic effect of perspective when combined with the blurry effect of the snowballs that are further away.
33) No Div Car CSS animation
Here abxlfazl khxrshidi has gone a step further, and made this CSS animated background of a car (one that’s gonna get pulled over very soon by the looks of it!), with no div at all!
Check for yourself, the HTML box is empty, apart from comments. How they’ve done it, is to apply all their CSS to the html element.
It’s pretty amazing what you can come up with when you’ve mastered your craft! But one of the cool things about front-end web development is that we can use code snippets, libraries, and CSS frameworks made by people much more skilled than us. That way, we don’t have to wait until we reach mastery to start making really cool stuff.
One such library I recommend you check out is fullPage.js.
fullPage helps you build full page sites — where you split your webpage into chunks, each taking up the full size of the user’s browser. You know the type — as you scroll, you move to the next page, rather than scrolling down just a little bit. Don’t know yet what I’m talking about? Just check out these 20 examples of one-page websites and your doubts will disappear.
How to Create a GIF Background for a Web Page

Animated Web page backgrounds can be eye-catching, and you can create them using GIF files. When you add text and other content to your business Web pages, you don’t have to worry about adding backgrounds: browsers simply give your pages white backgrounds if you don’t override that default. Add a short CSS class to an HTML Web page to use animated and stationary GIF images as the page’s background.
Open an HTML document and find the document's head section.
Paste the following code into that section:
This code defines a CSS selector that styles your document's body tag. The background-image attribute has a URL property whose value is "myImage.gif." Change that value to the name of one of your GIFs. The second line defines a background-repeat attribute whose value is "repeat" in this example. This value tells browsers to make the image repeat across the page and down the page to produce a grid effect. Delete that statement if you don't want your GIF to create a tiled background.
Save the document and view it in your browser to see the new background.
- Tizag.com: CSS Tutorial — Introduction
- W3Schools.com: CSS Background-Position Property
- Replace "repeat" with "repeat-x" if you want your GIF to repeat horizontally; replace it with "repeat-x" to make the image repeat vertically.
- Give the background color by adding "background-color:colorName" to the CSS code. Replace "colorName" with a color such as "Yellow" or "Blue." The GIF image will still appear in the background, but the background will also display the color you choose.
- If you choose an animated GIF as your background, it will move when site visitors view your page.
- Use JPEG or PNG files to display large images such as photographs. GIFs can only display 256 colors, and are usually used to display clip art, logos and other small images that don’t require many colors. However, you must use an animated GIF to animate your background. Animated GIFs often have large file sizes because the GIFs contain multiple images that create the illusion of motion. Use animated GIFs sparingly, and try to keep them as small as possible to help your Web pages load faster.
- You can also add a background-position attribute to your CSS, with values such as center, left top and right bottom. Add this attribute to make your GIF appear at specific locations in the background.
After majoring in physics, Kevin Lee began writing professionally in 1989 when, as a software developer, he also created technical articles for the Johnson Space Center. Today this urban Texas cowboy continues to crank out high-quality software as well as non-technical articles covering a multitude of diverse topics ranging from gaming to current affairs.