在div过渡时修复孩子的位置

时间:2018-08-28 06:35:19

标签: javascript css css3

我的设置如下

<div class=wrapper>
  <div class=element />
</div>

标记

.wrapper {
    height: 40px;
    width: 80px;
    border-style: solid;
    border-width: 2px;
    border-radius: 40px;
    border-color: red;
    display: flex;
    align-items: center;
    justify-content: center;
}

.element {
  background-color: hotpink;
  width: 10px;
  height: 10px;
}

.wrapper:hover {
    width: 800px;
    -webkit-transition: width 0.4s ease-in-out;
}

https://codepen.io/anon/pen/eLzGXY

现在,当我单击Icon时,Icon会在过渡时移到wrapper的中间。我希望它保持在其原始位置的左侧。我该怎么办?

3 个答案:

答案 0 :(得分:0)

恕我直言,有多种方法可以解决这个问题- 如果您不愿意使用定位,则可以将element的位置设置为绝对位置,并以一些狡猾的left来实现所需的目标。

.element {
  background-color: hotpink;
  width: 10px;
  position:absolute;
  left:37px;
  height: 10px;
}

https://codepen.io/anon/pen/OoXOPo#anon-login

或者我们可以将relative与父容器上的justify-items:start配合使用,以始终将element放置在其位置

https://codepen.io/anon/pen/eLzeZp

答案 1 :(得分:0)

要将正方形类元素保留在左侧,请删除:

    .wrapper {
       justify-content:center;
    }

,然后像这样对元素进行边距处理:

    .element {
        margin-left:35px;
    }

https://codepen.io/FEARtheMoose/pen/mGEqVL

答案 2 :(得分:0)

您可以在鼠标悬停时使用set css属性。

请参见下面的示例。

.wrapper {
    height: 40px;
    width: 80px;
    border-style: solid;
    border-width: 2px;
    border-radius: 40px;
    border-color: red;
    display: flex;
    align-items: center;
    justify-content: center;
}

.element {
  background-color: hotpink;
  width: 10px;
  height: 10px;
}

.wrapper:hover {
    width: 800px;
    -webkit-transition: width 0.4s ease-in-out;
    justify-content: left;
    padding-left:35px;
}
<div class=wrapper>
  <div class=element>
  </div>
</div>

相关问题