gpt4 book ai didi

html - 子元素的宽度过渡不适用于父元素

转载 作者:太空宇宙 更新时间:2023-11-04 05:43:21 25 4
gpt4 key购买 nike

我正在尝试实现一个我认为很简单的小效果:让子 div 在其父 div 悬停时扩大宽度,并让父 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 框的事实有关吗?我是否缺少 parent 的一些属性(property)?我也尝试在父级上添加 transition: all 4s,但没有成功。

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

感谢任何帮助!

最佳答案

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

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

问题是,如果 name 类的文本是动态的,你永远不会知道在转换时使用它的实际宽度,我已经使用 JavaScript< 解决了这个问题CSS 变量 来设置 :hover Action 中的实际宽度。

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

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>

关于html - 子元素的宽度过渡不适用于父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58934182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com