【问题标题】:Width transition on child element is not applied to parent子元素上的宽度过渡不适用于父元素
【发布时间】:2019-11-19 12:30:37
【问题描述】:

我正在尝试实现一个我认为很简单的小效果:让子 div 在其父级悬停时扩展宽度,并让父级的宽度在旁边过渡

重点强调我的问题是什么;就我到目前为止所取得的成就而言,当悬停父级时,它会立即扩展到最终的总宽度,就好像它事先知道其子级在过渡后的最终宽度一样,而子级确实过渡到了这个最终宽度。

这是一个说明问题的示例:

.profile {
  cursor: pointer;
  background-color: red;
  border-radius: 100px;
  padding-right: 10px;
  display: inline-flex;
  align-items: center;
}

.profile:hover .name {
  width: 100%;
}

.profile .picture {
  margin-right: 3px;
  display: inline-block;
  padding: 3px;
  width: 27px;
  height: 27px;
}

.profile .picture img {
  border-radius: 50px;
  width: 27px;
  height: 27px;
}

.profile .name {
  transition-property: width;
  transition-duration: 4s;
  width: 0;
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
}
<div class="profile">
  <div class="picture">
    <img src="https://s.gravatar.com/avatar/090a196b0a7db8a888d3b1af34e55cdc?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fja.png" alt="Avatar" />
  </div>
  <div class="name">John Doe</div>
</div>

我不明白为什么父母不遵循孩子的宽度。这与父级是flex 框有关吗?我错过了父母的一些财产吗?我也尝试在父级上添加transition: all 4s,但没有成功。

以某种方式使用translate 函数会更好吗?

任何帮助表示赞赏!

【问题讨论】:

  • @Paulie_D 哦。所以没有任何定义的父级width 意味着它有一个默认的auto 值。不知道那个。但是我不能为父级定义一个特定的width,因为它的宽度取决于它的内容(例如,用户的名字长度不同)。我不认为有一个 width 值允许转换和元素与它的内容一样宽,现在有吗?

标签: html css


【解决方案1】:

这是因为 .name 类的宽度在 px 中,而您的 .name:hover 的宽度在 % 中。

如果你想改变宽度过渡,你的类和它的悬停动作必须在同一个度量单位中。

问题是,如果 name 类的文本是动态的,你永远不会知道在转换时使用它的实际宽度,我已经使用 JavaScriptCSS variables 来设置:hover 操作中的实际宽度。

这可能不是最好的答案,但至少它有效!。

let width = document.getElementById('name').offsetWidth;
document.documentElement.style.setProperty('--w', width + "px");
document.getElementById('name').style.width = "0px";
:root{
  --w: 0;
}

.profile {
  cursor: pointer;
  background-color: red;
  border-radius: 100px;
  padding-right: 10px;
  display: inline-flex;
  align-items: center;
}

.profile:hover .name {
  width: var(--w)!important;
}

.profile .picture {
  margin-right: 3px;
  display: inline-block;
  padding: 3px;
  width: 27px;
  height: 27px;
}

.profile .picture img {
  border-radius: 50px;
  width: 27px;
  height: 27px;
}

.profile .name {
  transition-duration: 1s;
  display: inline-block;
  overflow: hidden;
  white-space:nowrap;
}
<div class="profile">
  <div class="picture">
    <img src="https://s.gravatar.com/avatar/090a196b0a7db8a888d3b1af34e55cdc?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fja.png" alt="Avatar" />
  </div>
  <div class="name" id="name">John Doe</div>
</div>

【讨论】:

  • 嗯......您确实在回答问题的理论部分,即知道为什么会发生这种行为。如果如您所说,我将宽度设置为实际值而不是 100%,则转换将完全按预期运行。
  • 您提出的解决方法似乎很容易实现,并且涉及的 JS 很少。这不是我所希望的,但我暂时接受这个答案。
猜你喜欢
  • 2016-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多