css 为什么::after元素在动画中改变了位置?[duplicate]

3pvhb19x  于 2023-03-20  发布在  其他
关注(0)|答案(1)|浏览(127)

此问题在此处已有答案

'transform3d' not working with position: fixed children(10个答案)
5天前关闭。
我正在尝试使用伪元素,我想知道为什么.container::after元素在动画过程中会改变它的位置。下面是HTML和CSS代码:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  height: 100vh;
}

header {
  position: sticky;
  top: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0.3rem;
  background-color: steelblue;
  z-index: 1;
}

main {
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  align-items: center;
  font-size: 2rem;
  background-color: grey;
  height: 100%;
  position: relative;
}

div {
  border: 10px solid red;
  background-color: white;
}

main:hover .container {
  transform: rotate(360deg);
  color: purple;
  transition: all 2s;
}

main .container::after {
  position: absolute;
  top: 200px;
  left: 100px;
  background-color: white;
  color: gold;
  content: "after div";
}
<header>
  <h1>stuff</h1>
</header>
<main>
  <div class="container">I am a container</div>
</main>

我试着把

position: relative

在div元素上。但这不是我想要的。显然::after元素在动画中与它的父元素(div)相关,但为什么会这样呢?我能避免吗?

z31licg0

z31licg01#

我不太清楚你想要实现什么,但是你可以创建一个包含两个元素的group元素,一个是::before元素,现在是一个普通的div,另一个是你的.container元素。
然后如果你只给予.container元素一个动画,::before元素不会移动,因为它不在另一个里面。
下面是代码:
超文本:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
<header>
    <h1>stuff</h1>
</header>
<main>
    <div class="container">I am a container</div>
    <div class="previousAfter">after div</div> <!-- I added this line -->
</main>
</body>
</html>

CSS:

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    height: 100vh;
}

header {
    position: sticky;
    top: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0.3rem;
    background-color: steelblue;
    z-index: 1;
}

main {
    display: flex;
    flex-flow: column nowrap;
    justify-content: center;
    align-items: center;
    font-size: 2rem;
    background-color: grey;
    height: 100%;
    position: relative;
}

div {
    border: 10px solid red;
    background-color: white;
}

main:hover .container {
    transform: rotate(360deg);
    color: purple;
    transition: all 2s;
}

main .previousAfter { /* I changed this line */
    position: absolute;
    top: 200px;
    left: 100px;
    background-color: white;
    color: gold;
}

如果这是你要找的东西就告诉我。

相关问题