基于CSS伪元素实现Hover带过渡动画的按钮开发需求
The main issue with your original code is that CSS transitions don’t work on changes to the content property. Instead of toggling the text on hover, we need to have the text present but hidden initially, then animate its visibility and position smoothly. Here’s the refactored code that achieves the transition effect you’re looking for:
Revised CSS
.back-button { font-weight: bold; letter-spacing: normal; line-height: 100%; text-align: center; text-decoration: none; border-radius: 0; box-shadow: none; padding: 5px 5px 5px 5px; /* Adjusted right padding to accommodate sliding text */ color: #181818; font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; font-size: 12px; display: inline-flex; align-items: center; /* Vertically centers icon and text */ position: relative; } .back-button::before { margin-right: 10px; background-image: url('https://mcusercontent.com/ec104f3d77537e1962ab6441c/images/d7bb4928-a156-4682-9677-d0d5b47c3a21.png'); background-size: 40px 40px; display: inline-block; width: 40px; height: 40px; border-radius: 50%; content: ""; } .back-button::after { content: "Home"; opacity: 0; transform: translateX(-10px); /* Start text slightly left of final position */ transition: opacity 0.4s ease, transform 0.4s ease; /* Animate opacity and position */ white-space: nowrap; /* Prevent text wrapping */ } .back-button:hover::after { opacity: 1; transform: translateX(0); /* Slide text to normal position */ margin-left: 10px; /* Add spacing between icon and text */ } .mcnButton { transition: all 0.4s ease; /* Apply transition to all button properties */ border-radius: 50px !important; box-shadow: #999 0 0 20px 0 !important; outline: none; user-select: none; background: transparent; } .mcnButton:focus { background: #eceff9 !important; color: #181818 !important; }
Revised HTML
<div style="display:flex;"> <a class="back-button mcnButton" href="https://www.example.com/" target="_self"></a> </div>
Key Changes Explained:
- Persistent Text with Hidden State: The "Home" text is now always present in the
::afterpseudo-element, but hidden usingopacity: 0and shifted left withtransform: translateX(-10px). - Smooth Transition: We added transitions to the
opacityandtransformproperties of the::afterelement, so it fades in and slides into place on hover. - Vertical Alignment: Using
display: inline-flexandalign-items: centerensures the icon and text stay perfectly aligned vertically. - Consistent Button Transitions: The
.mcnButtonclass now usestransition: all 0.4s easeto make any property changes (like background color on focus) animate smoothly.
This setup mimics the smooth hover effect from your reference site, with the text sliding in seamlessly when the cursor hovers over the button.
内容的提问来源于stack exchange,提问作者Nicolas
相关产品推荐
相关产品推荐

