如何仅使用 CSS 和 HTML 来约束动画?

How do I constraint an animation using only CSS and HTML?

对于学校项目,我正在按照本教程进行 Pong 游戏:http://www.sitepoint.com/css3-pong-insane-things-to-do-with-css/

我卡在动画部分了。球没有居中,当我将 @keyframes 向上放置时,它会使球在 球场上上下弹跳,当我希望它限制在球场(墙壁)内时。

See a picture here

如何让球留在盒子里?

这是我的 HTML:

<!doctype html>
<meta charset="UTF-8">
<title>Pong (1972)</title>
<link href="styles/csspong.css" rel="stylesheet">

<h1>CSS PONG</h1>
<div id="court">
    <div id="horizontal">
    <span id="ball"></span>
    </div>
</div>

CSS:

/*********************
    PLATFORM
********************/

#court{ 
    margin: 30px auto;
    width: 600px;
    height: 300px;
    position: relative;
    border: 4px dotted #3f3;
}

#court:before{
    left: 50%;
    content:'';
    width: 10px;
    height: 300px;
    position: absolute;
    border-left: 4px dashed #3f3;
    }

/*********************
        BALL
********************/

#ball{
    position: absolute;
    width: 20px;
    height: 20px;
    display: block;
    background :#3f3;
    border-radius: 50%;
    transform: translate3d(10px,0,0)
}

/*********************
    BALL ANIMATION
********************/

@keyframes leftright {
0%,100% {transform: translate3d(10px,0,0)}
50% {transform: translate3d(570px,0,0)}
}
#ball{
 ...
 animation: leftright 2s infinite linear
 }

 @keyframes updown {
 0%,50%,100% {transform: translate3d(0,0,0)}
 25% {transform: translate3d(0,142px,0)}
 75% {transform: translate3d(0,-136px,0)} }

 #horizontal{
 ...
 animation: updown 2s infinite linear; }

首先,您需要从 #ball#horizontal 中的 CSS (x2) 中删除 ...

然后需要加上#balltop:142px,就是框的高度(150px)减去边框的总像素(8px)的一半。

Here is my fiddle of it.

/*********************
PLATFORM
********************/

#court{ 
    margin: 30px auto;
    width: 600px;
    height: 300px;
    position: relative;
    border: 4px dotted #3f3;
}

#court:before{
    left: 50%;
    content:'';
    width: 10px;
    height: 300px;
    position: absolute;
    border-left: 4px dashed #3f3;
}

/*********************
    BALL
********************/

#ball{
    top:142px;
    position: absolute;
    width: 20px;
    height: 20px;
    display: block;
    background :#3f3;
    border-radius: 50%;
    transform: translate3d(10px,0,0)
}

/*********************
BALL ANIMATION
********************/

@keyframes leftright {
    0%,100% {transform: translate3d(10px,0,0)}
    50% {transform: translate3d(570px,0,0)}
}
#ball{

     animation: leftright 2s infinite linear
 }

@keyframes updown {
    0%,50%,100% {transform: translate3d(0,0,0)}
    25% {transform: translate3d(0,142px,0)}
    75% {transform: translate3d(0,-136px,0)} }

#horizontal{
    animation: updown 2s infinite linear; 
}