


CSS Child element animation when parent element hovers: Tips for implementing the transition between text and lines
Problem background and challenges
In front-end development, adding animation effects to interactive elements is a common way to improve user experience. A typical scenario is a navigation menu, where each menu item is usually composed of a list item
- Line Animation: A dynamic underscore or decorative line appears below or above the link text.
- Text animation: The link text itself moves slightly upward.
The original code structure often applies line animations (implemented via ::before or ::after pseudo-elements) directly to the element. For example, when is hovered, its pseudo-element changes width or transparency to simulate the appearance of a line.
Original CSS example (line animation applied to a):
.snip1168 a:before { top: 0; display: block; height: 3px; width: 0%; content: ""; background-color: black; position: absolute; transition: all 0.35s ease; } .snip1168 a:hover:before { opacity: 1; width: 100%; }
At this time, if you add transform: translate(0, -10px); directly on the element to achieve text upward movement, you may encounter the following problems:
- Animation conflict: transform may conflict with pseudo-element positioning or animation.
- Overall Movement: If the element is shifted overall, the pseudo-elements (i.e. lines) inside it will also move, which may not be the effect we want, and we want the lines to remain in place or animation independently.
The core challenge is how to trigger the independent bit movement of the internal text when the parent element
Core Solution: Separation of Responsibilities
The key to solving this problem lies in "separation of responsibilities". We assign different animation effects to the most appropriate elements to be responsible for:
- Line animation: Transfers the line generation and animation logic from the element to its parent element
- . This way, when
- hovers, it will be responsible for triggering the appearance of the line.
- Text bit movement painting: Keep text bit movement painting applied to elements. When
- is hovered, the transform displacement of the element is triggered by the CSS selector li:hover a.
In this way,
Code implementation and parsing
The following is the CSS code optimized according to the above strategy, with detailed analysis.
The HTML structure remains the same:
<div class="'container'"> <main class="'main'"> <div class="'nav'"> <div class="'navIcon'"> <img src="/static/imghw/default1.png" data-src="https://picsum.photos/40" class="lazy" height="{40}" style="max-width:90%" alt="CSS Child element animation when parent element hovers: Tips for implementing the transition between text and lines" > </div> <ul class="'snip1168'"> <li class="'current'"><a href="#" data-hover="Work">Work</a></li> <li><a href="#" data-hover="Recs">Recs</a></li> <li><a href="#" data-hover="Say Hi">Say Hi</a></li> </ul> </div> </main> </div>
Optimized CSS code:
/* The general style remains unchanged*/ html, body { padding: 0; margin: 0; font-family: "sequel-sans-roman", -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif; } .container { padding: 0 2rem; } .main { min-height: 100vh; padding: 4rem 0; flex: 1; display: flex; flex-direction: column; justify-content: center; align-items: center; } a { color: inherit; text-decoration: none; } * { box-sizing: border-box; } .navIcon { display: inline-block; flex-grow: 1; } .nav { display: flex; justify-content: space-between; width: 100%; margin-top: 2.4em; /* Coordination and link distance*/ } .snip1168 { text-align: center; text-transform: uppercase; } .snip1168 * { box-sizing: border-box; } /* Modify the li element*/ .snip1168 li { display: inline-block; /* Make sure li can set width and position pseudo-elements*/ list-style: none; margin: 0 1.5em; padding: 2.4em 0 0.5em; /* The padding originally on a is moved to li */ color: rgba(0, 0, 0, 1); position: relative; /* Provides positioning context for pseudo-elements*/ text-decoration: none; /* background: pink; /* for debugging, you can delete */ */ } /* Move line pseudo-element style from a to li */ .snip1168 li:before, .snip1168 li:after { position: absolute; -webkit-transition: all 0.35s ease; transition: all 0.35s ease; } .snip1168 li:before { top: 0; display: block; /* Pseudo-elements usually require block or inline-block to set width and height*/ height: 3px; width: 0%; content: ""; background-color: black; } /* li triggers line animation when hovering*/ .snip1168 li:hover:before, .snip1168 .current li:before { /* The activation status is also applied*/ opacity: 1; width: 100%; } /* Another pseudo-element (if present) */ .snip1168 li:hover:after, .snip1168 .current li:after { max-width: 100%; } .mainText { text-transform: uppercase; font-size: 1.1rem; } /* Add text bit movement to element a*/ .snip1168 li a { transition: transform ease 400ms; /* Define the transition effect of transform animation*/ transform: translate(0, 0); /* Initial state, text does not shift*/ display: inline-block; /* Ensure that the transform attribute takes effect*/ } /* When li hovering, the element a moves upward*/ .snip1168 li:hover a { transform: translate(0, -10px); /* The text moves upward by 10px */ }
Key code point analysis:
-
.snip1168 li modification:
- display: inline-block;: Ensure that the
- element can set width, height, and positioning context as position: relative.
- padding: 2.4em 0 0.5em;: The margins originally applied to are now transferred to
- to provide enough space for lines and text.
- position: relative;: This is a crucial step. It provides the location context for the ::before and ::after pseudo-elements inside
- so that these pseudo-elements can be absolutely positioned relative to
- without being affected by the displacement of the element.
-
Transfer of line pseudo-elements (::before, ::after):
- Change the target selector for style rules such as .snip1168 a:before and .snip1168 a:hover:before to .snip1168 li:before and .snip1168 li:hover:before. This means that the line is now a pseudo-element of the
- element, and its animation is controlled by the hover state of the
- .
- display: block; (or inline-block): The pseudo-element is an inline element by default, and needs to be set to block or inline-block to correctly set width and height.
-
Text bit movement painting (.snip1168 li a):
- display: inline-block;: transform attribute is invalid for inline element. Setting to inline-block allows it to accept transform animations while remaining in the text stream.
- transition: transform ease 400ms;: Defines a smooth transition effect for the transform property, lasting 400ms.
- transform: translate(0, 0);: This is the default (non-hover) state of the element, ensuring that the text is in its original position without hovering.
- .snip1168 li:hover a { transform: translate(0, -10px); }: When the parent element
- is hovered, the transform attribute of its child element changes, causing the text to move upward by 10 pixels. Due to the transition set, this change will be a smooth animation.
Through the above modification, line animation and text bit movement art are now responsible for
Notes and best practices
- Importance of Positioning Contexts: When using position: absolute to locate a pseudo-element, be sure that its parent (or ancestor element) has position: relative, absolute, or fixed. Otherwise, the pseudo-element will be positioned relative to the nearest positioning ancestor or the initial inclusion block, which may lead to an unexpected layout.
- Applicability of transform: The transform attribute is only effective for non-inline elements (such as block, inline-block, table-cell, etc.). Therefore, if you try to apply transform to the element of the default inline, you need to set its display property to inline-block or block.
- Animation performance: Priority is given to using transform and opacity for animation. These properties are usually GPU-accelerated by the browser, and their performance is better than changing width, height, top, left, etc., which will trigger the reflow and repaint of the publishing layout.
- Setting of transition attributes: The transition attribute should be set on the non-hover state of the element, that is, .snip1168 li a, not li:hover a. In this way, the animation can smoothly transition whether it is entering a hover state or leaving a hover state.
- Code readability and maintenance: Clear animation responsibilities and organize relevant styles together will help improve the readability of the code and future maintenance. For example, place all the lines-related styles under li and its pseudo-elements, and place text displacement-related styles under a element a.
- Activation state handling: The example includes .current li:before and .current li:after, which are used to handle the line styles of the currently activated navigation items. This is a good practice to ensure that the activation state also maintains visual consistency.
Summarize
By carefully dividing the responsibilities of CSS animations, we can effectively solve the complex problems of child element animation when the parent element is hovered. By transferring the logic of line animation to the parent element
The above is the detailed content of CSS Child element animation when parent element hovers: Tips for implementing the transition between text and lines. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

This tutorial details how to use CSS to accurately hide specific text content in HTML pages to avoid the problem of the entire parent element being hidden due to improper selectors. By adding exclusive CSS classes to the wrapping elements of the target text and using the display: none; attribute, developers can achieve refined control of page elements, ensuring that only the required parts are hidden, thereby optimizing page layout and user experience.

This article explores the challenge of capturing mousedown events on parent divs containing cross-domain iframes. The core problem is that browser security policies (same-origin policy) prevent direct DOM event listening on cross-domain iframe content. This type of event capture cannot be achieved unless the iframe source domain name is controlled and CORS is configured. The article will explain these security mechanisms in detail and their limitations on event interactions and provide possible alternatives.

When using Bootstrap for web page layout, developers often encounter the problem of elements being displayed side by side rather than stacked vertically by default, especially when the parent container applies Flexbox layout. This article will explore this common layout challenge in depth and provide a solution: by adjusting the flex-direction attribute of the Flex container to column, using Bootstrap's flex-column tool class to achieve the correct vertical arrangement of H1 tags and content blocks such as forms, ensuring that the page structure meets expectations.

UseCSSfloatpropertytowraptextaroundanimage:floatleftfortextontheright,floatrightfortextontheleft,addmarginforspacing,andclearfloatstopreventlayoutissues.

Usemailto:inhreftocreateemaillinks.Startwithforbasiclinks,add?subject=and&body=forpre-filledcontent,andincludemultipleaddressesorcc=,bcc=foradvancedoptions.

Setthelangattributeinthehtmltagtospecifypagelanguage,e.g.,forEnglish;2.UseISOcodeslike"es"forSpanishor"fr"forFrench;3.Includeregionalvariantswithcountrycodeslike"en-US"or"zh-CN";4.Applylangtospecificelementswhe

This article explores two common problems when calling external JavaScript functions in HTML: improper script loading time causes DOM elements to be unready, and function naming may conflict with browser built-in events or keywords. The article provides detailed solutions, including tweaking script reference locations and following good function naming specifications to ensure JavaScript code is executed correctly.

UsethetitleattributeforsimpletooltipsorCSSforcustom-styledones.1.Addtitle="text"toanyelementfordefaulttooltips.2.Forstyledtooltips,wraptheelementinacontainer,use.tooltipand.tooltiptextclasseswithCSSpositioning,pseudo-elements,andvisibilityc
