how to change html background dynamically
I have a page which has a style like this in a css file:
and I have either a javascript which is loaded after window.onload and causes page to be expand vertically and so the rest of my page will become black. how can I apply the background image to my page again after the javascript code is completed?
![]()
8 Answers 8
jQuery:
Non-jQuery:
Assign Body an ID: <body >
or as John mentioned
and furthermore, a T POPs Mentioned, make sure it goes at the end:
i think inserting this at the end of a document could work:
Some browsers have a bug (chrome, safari) where they do not expand the html body background correctly until a reload occurs. Depending on what you are actually doing in your javascript, there may not be a solution here.
The CSS style ‘repeat-x’ sets the background to only expand horizontally and not vertically. Removing that part from the code will make sure your background repeats in both X (horizontal) and Y (vertical) directions.
which shows a way to achieve what you want via Javascript.
Try this using Javascript, just form a array in script and use a random method http://suzzcodes.com/how-to-change-the-website-background-dynamically/
Well, if you are like me and you are new to javascript and jQuery you will find this task a lot formidable. But you are in luck, because I have found a solution. Try this:
Link jQuery before doing this:
and do this in CSS:
What this mainly does is it gives the body a class of second and in css second has a different background image as the body so it overites the body css rule // I think // I am also new to this //
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.
Слайдер фонового изображения или меняющийся фон сайта с помощью CSS

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

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

HTML разметка
Тут все очень просто, нужно просто добавить UL-список в самое начало сразу после тега body.
В списке всего три строки li, то есть слайдер рассчитан на 3 изображения, если нужно больше, то первым шагом будет добавление еще нужного количества строк. Двигаемся дальше.
CSS стили
Тут наверное самая основная часть работы, так как от CSS, зависит то как будет работать наш слайдер. Открываем файл стиле вашего сайта и добавляем в него следующий код.
Если Вы разбираетесь в CSS, то для Вас не составит труда понять, что за что отвечает. Расскажу по минимуму, потому как обучать CSS, нет смысла.
Наш список со слайдами имеет класс body_slides. Ему заданы стили, для внешнего вида и общих настроек.
Далее у нас идет псевдоэлемент — :after, который задает дополнительный слой и поверх фона наложен узор в виде точек. Делается это с помощью изображение, к которому указан путь images/pattern.png. Если у Вас другой путь, то укажите его правильно.
.body_slides li:nth-child(1) — это первый по порядку слайд и ему задан фоновый рисунок. Далее идет nth-child(2), ему кроме рисунка задано еще время и равно 6 сек. То есть, он появится через 6 секунд после первого слайда. Далее nth-child(3), он появится еще через шесть секунд, поэтому у него время 12 сек. Если нужно добавить 4 слайд, то добавляем nth-child(4) и у него должно быть время уже 18 секунд. Думаю тут понятно.
Далее нужно указать полное время анимации, оно сейчас задано в body_slides li и равно 18 сек. Если добавите 4 слайд то будет равно 24 и так далее. Если с математикой дружите, должны справится, главное не ошибиться ибо слайдер ровно не заработает. По желанию можно ускорить или замедлить, прописав нужное время.
keyframes anim_slides — это появление и исчезновении слайда. Изначально слайд прозрачный и ему задано условие — opacity:0;. Когда приходит очередь любого из слайдов, он сначала появляется, а потом начинает вновь становится прозрачным и полностью исчезает, а на его месте появляется новый. В данном примере — 3 слайда и 100% анимации это время перелистывания всех слайдов, а не одного. Поэтому слайд первый появляется виден и исчезает на 30%(максимально можно 33.3%) потому как, если 100% разделить на 3 слайда — получится 33,3%. Если бы у вас было 4 слайда — то 25%. То бишь, нужно показать появление, показ и исчезновение слайда за 25% от общих 100%. В нашем примере с 3 слайдами. Слайд появляется от 0 до 6%, виден от 6 до 24% и исчезает от 24 до 30%. Если хотите изменить скорость появления или исчезновения, меняйте проценты — это процент от общего времени. От правильности указания процентов — зависит и правильность работы слайдера.
Остальные настройки уже по желанию и нужде — общий фон, сейчас черный, путь к картинкам, позиционирование, уровень слоя и тд. Преимущество данного слайдера в том, что он простенький и не использует скриптов и целых библиотек, если бы он был сделан с помощью — jQuery. Очень надеюсь, что если Вы хотели себе смену фоновых картинок то данный CSS слайдер, Вам поможет.
На этом все, спасибо за внимание.
Якщо Вам була корисна моя праця, можете фінансово підтримати сайт або відключити блокувальник реклами, що займе 2 хвилини 🙂
Как сделать анимированный фон на странице

Пару дней назад мне задали вопрос по поводу того, как сделать анимированный фон на странице. При этом человек знал и про 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 (что в прочем и так по умолчанию стоит!) И всё стало норм!:)
У меня почему-то не получилось задать фон таким способом.
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.