如何将CSS Transition动画从左向右改为从右向左?
实现从右向左展开的按钮标签过渡效果
问题说明
现有按钮hover时标签从左向右展开,需要修改为从右向左的过渡动画效果。
修改后的代码
CSS代码
a { color: #000; text-decoration: none; } a.button { position: relative; display: inline-flex; align-items: center; /* 改为靠右对齐,为标签从右向左展开提供空间 */ justify-content: flex-end; overflow: hidden; padding: 8px; border: 1px solid #ccc; border-radius: 8px; background: #eee; transition: .2s; .material-icons { font-size: 24px; transition: .2s; } .label-hidden { max-width: 0; opacity: 0; max-height: 1em; white-space: nowrap; transition: .2s; /* 初始状态下标签在图标右侧,无间距 */ margin-right: 0; } &:hover { .label-hidden { max-width: 200px; /* hover时标签向左移动,露出间距 */ margin-right: 8px; opacity: 1; } } }
HTML代码
<a class="button button-small" target="_blank" rel="noopener noreferrer" href="https://www.google.com/maps/search/Station Name"> <span class="label-hidden">Show location</span> <i class="material-icons">map</i> </a>
修改要点
- 布局调整:将按钮的
justify-content从flex-start改为flex-end,让内部元素靠右排列;同时互换HTML中标签与图标的顺序,标签在前、图标在后。 - 过渡方向调整:将原
margin-left改为margin-right,hover时通过增加右侧间距,让标签从右向左“滑入”显示。 - 保持过渡连贯性:保留原有的
max-width和opacity过渡属性,确保展开/收起动画平滑自然。
内容的提问来源于stack exchange,提问作者Ricky
相关产品推荐
相关产品推荐

