Charles Angerstein Charles Angerstein - 6 months ago 25
CSS Question

CSS animation extends past edge of screen

I have created an animation in the background of the browser window. It's clouds floating past. I managed to make them start off screen so they flow in naturally but I can't figure out how to make them flow off screen and disappear. Currently they continue past the edge of the screen causing the browser window to expand until the animation finally stops. The correct behaviour would be for the animation to start off screen and continue to the edge of the screen and beyond, disappearing as it leaves the div containing it. Here's the code:

HTML

<div class="page-content">
<div class="cloud1">
<img src="~/Images/sunwave-cloud1.png" />
</div>
<div class="cloud2">
<img src="~/Images/sunwave-cloud2.png" />
</div>
<div class="cloud3">
<img src="~/Images/sunwave-cloud3.png" />
</div>
<div class="cloud4">
<img src="~/Images/sunwave-cloud4.png" />
</div>
<!--CONTENT START-->
<div class="box">
@RenderBody()
</div>
<!--CONTENT END-->
</div>


CSS

.page-content {
font-family: HelveticaNeue;
margin-left: 10%;
margin-right: 10%;
padding-top: 50px;
padding-bottom: 100px;
max-width: 100%;
height: auto;
text-align: center;
}

.cloud1 {
animation-name: cloud1;
animation-duration: 25s;
animation-iteration-count: infinite;
position: absolute;
top: 100px;
left: -488px;
z-index: -1;
}

.cloud2 {
animation-name: cloud2;
animation-duration: 25s;
animation-delay: 10s;
animation-iteration-count: infinite;
position: absolute;
top: 200px;
left: -215px;
z-index: -1;
}

.cloud3 {
animation-name: cloud3;
animation-duration: 20s;
animation-delay: 7s;
animation-iteration-count: infinite;
position: absolute;
top: 300px;
left: -421px;
z-index: -1;
}

.cloud4 {
animation-name: cloud4;
animation-duration: 30s;
animation-delay: 10s;
animation-iteration-count: infinite;
position: absolute;
top: 400px;
left: -359px;
z-index: -1;
}


So the question is, to be clear, how do I change this code (preferably using pure css) so that the clouds do not expand the window and and the animation stops after they have left the screen.

Answer

There's a css property called overflow. It specifies what happens if your content overflows an element's box. In your case your parent element page-content should have: overflow: hidden;.

In case that does not work you can add that same property to your body tag and prevent any element to overflow it with body { overflow: hidden; }.

More info on overflow property here.

UPDATE:

Overflow can be both horizontal and vertical. overflow-x and overflow-y respectively.

In order for overflow hidden to work with children elements that have position: absolute, you need to specify in your parent element the css property position: relative.

(In your case your element with class "wrapper" is the parent and should have position relative, note: Unwrap your header from the wrapper element.)

Here's a quick demo: jsfiddle.