如何让右侧浮动的搜索栏hover时向右而非向左展开
该需求完全可以实现,你当前代码向左展开的核心原因是input使用left定位、宽度增大时向左侧延伸,且按钮未和输入框做联动定位,调整CSS属性即可实现预期效果。
HTML代码保持原有写法即可,修改后的CSS代码如下:
.search { position: relative; border-radius: 40px; height: 40px; width: 40px; /* 初始宽度和按钮一致,仅显示按钮 */ background-color: orange; float: right; transform: translate(-280px, 5px); transition: 0.2s; /* 整个搜索栏宽度和位移加过渡 */ overflow: hidden; } /* hover时搜索栏整体向右移动同时变宽,实现向右展开效果 */ .search:hover { width: 190px; /* 输入框宽度150 + 按钮宽度40 */ transform: translate(calc(-280px + 150px), 5px); /* 向右移动150px,对应输入框宽度 */ } .search input { position: absolute; left: 20px; top: 8px; padding: 5px; outline: none; width: 150px; /* 输入框固定宽度 */ border-radius: 20px 0 0 20px; /* 圆角调整到左侧 */ border: none; background: transparent; } .btn { position: absolute; right: 0; /* 按钮始终贴在搜索栏最右侧 */ height: 40px; width: 40px; border-radius: 20px; background-color: tomato; } .btn i { position: relative; top: 12px; left: 12px; }
核心改动点说明:
- 给
.search新增相对定位、固定初始宽度、过渡属性和溢出隐藏,默认仅显示搜索按钮 - hover时同时调整
.search的宽度和水平位移,实现左边界不动、右边界向右延伸的展开效果,符合你要求的向右展开逻辑 - 按钮设置为绝对定位贴在
.search右侧,搜索栏宽度变化时自动同步移动到最右侧,无需额外配置 - 调整输入框的圆角方向,固定输入框宽度,跟随搜索栏的宽度变化自动显隐,过渡效果更流畅
内容的提问来源于stack exchange,提问作者kriloots
相关产品推荐
相关产品推荐

