Zip Zip - 3 months ago 10
CSS Question

Apply CSS Animation to only one div

Problem: why is the

div
with
id="test"
being animated when I only apply animation to the
div with class content
?

Question: How to animate only the div with class "content"?



.content{
display: flex;
flex: 1;
flex-direction: row;
justify-content: space-between;
margin: 0 50px 0 50px;
flex-wrap: wrap;
animation-name: bla;
animation-duration: 4s;
margin-top: 50px;
}

.item{
color: white;
width: 300;
height: 300;
}

h4{
font-size: 24px;
background-color: #3498DB;
text-align: center;
}

img{
margin-bottom: -20px;
}

@keyframes bla {
from { margin-top: -50px }
to { margin-top: 50px; }
}

<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div class="container">
<div class="content">
<div class="item">
<img id="1" src="1.jpg">
<h4>1</h4>
</div>
<div class="item">
<img id="2" src="2.jpg">
<h4>2</h4>
</div>
<div class="item">
<img id="3" src="3.jpg">
<h4>3</h4>
</div>
</div>
</div>

<div id= "test">
<p>hello</p>
</div>
</body>
</html>




Answer

Use a transform/translation instead of margin:

.content {
  display: flex;
  flex: 1;
  flex-direction: row;
  justify-content: space-between;
  margin: 0 50px 0 50px;
  flex-wrap: wrap;
  animation-name: bla;
  animation-duration: 4s;
  transform: translateY(50px);
}
.item {
  color: white;
  width: 300;
  height: 300;
}
h4 {
  font-size: 24px;
  background-color: #3498DB;
  text-align: center;
}
img {
  margin-bottom: -20px;
}
@keyframes bla {
  from {
    transform: translateY(-50px);
  }
  to {
    transform: translateY(50px);
  }
}
<html>

<head>
  <title>Test</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <script type="text/javascript" src="script.js"></script>
</head>

<body>
  <div class="container">
    <div class="content">
      <div class="item">
        <img id="1" src="1.jpg">
        <h4>1</h4>
      </div>
      <div class="item">
        <img id="2" src="2.jpg">
        <h4>2</h4>
      </div>
      <div class="item">
        <img id="3" src="3.jpg">
        <h4>3</h4>
      </div>
    </div>
  </div>

  <div id="test">
    <p>hello</p>
  </div>
</body>

</html>

Comments