如何使用CSS无缝地扩大/缩小悬停元素?



我是一个很新的编码,我只是想做一些基本的CSS。我有一个登陆页,中间分成两个。左边是黄色的分格,右边是灰色的分格。当我将鼠标悬停在div上时,它会增加其宽度(左div为ltr,右div为rtl)。在相同的悬停事件,我希望其他div减少其宽度。所以两者之间没有重叠

的代码,我有左边的div作品。悬停事件也可以工作。当我把鼠标悬停在左边时。宽度变为51%,右边div的宽度变为49%。然而,右侧的等效物不起作用。当我停在右边的时候。右侧div增加其宽度,但左侧div不减小到49%。右边刚好和左边重叠。

任何想法?我找到了一些关于父母和孩子关系的答案,但没有成功。

为我写得不好的代码道歉。我刚开始工作,希望能得到一些建议。

#leftside {
/*this is the orange half*/
height: 100%;
width: 50%;
position: absolute;
left: 0;
top: 0;
opacity: 0.5;
background-image: linear-gradient(rgba(255, 255, 0, 1), rgba(255, 165, 0, 1));
transition: all 1s;
}
#leftside:hover {
opacity: 1.0;
width: 51%;
}
#leftside:hover+#rightside {
width: 49%
}
#rightside {
/*this is the grey half*/
height: 100%;
width: 50%;
position: absolute;
right: 0;
top: 0;
opacity: 0.5;
background-image: linear-gradient(rgba(255, 255, 255, 0), rgba(160, 160, 160, 1));
transition: all 1s;
}
#rightside:hover {
opacity: 1.0;
width: 51%;
}
#rightside:hover+#leftside {
width: 49%
}
<div id="leftside">
<a class="leftsidehome" href="page1.html"></a>
</div>
<div id="rightside">
<a class="rightsidehome" href="page2.html"></a>
</div>

你的代码的问题是#rightside:hover+#leftside,因为CSS不能回头。下面是使用flexbox的可能解决方案。

.container {
display: flex;
width: 100%;
}
#leftside,
#rightside {
flex-grow: 1; /* Allow each flex item to grow */
flex-shrink: 1; /* Allow each flex item to shrink */
width: 50%;
height: 100px; /* Used only to make them visible */
transition: width 1s; /* Animate the change of width */
}
#leftside {
background: yellow;
}
#rightside {
background: grey;
}
#leftside:hover {
width: 51%;
}
#rightside:hover {
width: 51%;
}
<div class="container">
<div id="leftside">
<a class="leftsidehome" href="page1.html"></a>
</div>
<div id="rightside">
<a class="rightsidehome" href="page2.html"></a>
</div>
</div>

最新更新