如何重叠包含形状的元素

How do I overlap elements containing shapes

我想要的是让每边的两个方块合在一起成为一个,即在包装纸的中心一个重叠另一个。我遇到的问题是,一旦它们聚在一起,其中一个正方形就会下降一个级别。我不确定这是使用 jQuery 还是使用 CSS.

实现的

请看我的program here

$(document).ready(() => {
  $(".square").animate({
    backgroundColor: "red",
  }, 3000);

  $("#squareOne").animate({
    marginLeft: "+=45%",
  }, 800);

  $("#squareTwo").animate({
    marginRight: "+=45%",
  }, 800);
});
#wrapper {
  width: ...;
  margin: 100px auto;
  border: 1px solid black;
}

.square {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  margin: 10% 30px;
}

#squareTwo {
  position: relative;
  float: right;
}

#squareOne {
  position: relative;
  background: #fff;
}


}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
  <div id="wrapper">
    <div class="square" id="squareOne"></div>
    <div class="square" id="squareTwo"></div>
  </div>
</body>

问题出在你使用maring。但是 margin 确实会将其他对象推离它。
使用而不是保证金 position: relative; 而只是 left: 800px; 和另一个 right: 800px;
现在不应该跳来跳去。

如果你想让方块重叠,它们必须绝对定位。

然后,有一个关于行进距离的计算...

$(document).ready(() => {
  $(".square").animate({backgroundColor: "red"},3000);
  
  // Calculate the slide distance
  // That is half the wrapper width minus the half of the square width
  let distanceToTravel = $("#wrapper").width() / 2 - $(".square").outerWidth() / 2;

  $("#squareOne").animate({marginLeft: distanceToTravel},800);
  $("#squareTwo").animate({marginRight: distanceToTravel},800);
});
#wrapper {
  margin: 100px auto;
  border: 1px solid black;
  position: relative;
  display: flex;
  justify-content: space-between;
  
}
.square {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  margin: 10% 30px;
  position: absolute;
}

#squareTwo {
  right: 0;
}
<head>
  <meta charset="utf-8">
  <title>JavaScript</title>
  <link rel="stylesheet" href="styles/styles.css">
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script src="scripts/fma_t5.js"></script>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
  <div id="wrapper">
    <div class="square" id="squareOne"></div>
    <div class="square" id="squareTwo"></div>
  </div>
</body>