Tips for activating hover effect on child components by hovering over the parent container?

At the moment, I am tackling an issue with CSS in a nextJS web application. The problem lies in a parent div element that contains multiple child elements. My goal is for hovering over the parent div to trigger changes on the child elements as well.

Here's a simplified version of my code:

export default function portfolio() {
return (
    <div className={homeStyles.mainContent}>
        <div className={homeStyles.titleNum}>
            <h2>01</h2>
        </div>
        <div className={homeStyles.titleName}>
            <h2>Telegram Bot</h2>
        </div>
    </div>
    )
}

When the parent div (.mainContent) is hovered over, I want the background color to change and also have the child elements (Title Number and Title Name) alter their font color and size simultaneously.

Could someone guide me on achieving this in nextJS? Thank you.

EDITED

Is the following approach effective?

<div class="main">
      <div class="num">Num</div>
      <div class="name">Name</div>
</div>
.main {
  background: blue; 
}

.main:hover {
  background: green;
}

.main:hover .num,
.main:hover .name {
  color: red;
  font-weight: bold;
}

Any suggestions on improving this process? It feels cluttered, especially when dealing with multiple child elements simultaneously. Is there a way to make the code more concise and elegant?

Answer №1

For adding a hover effect in HTML and CSS, remember to include > after the hover selector followed by the .classname of the element you want to change.

  • Note that this method may not be effective for all cases, but it generally works well with pure HTML and CSS.

.parentClass{
    height: 300px;
    width: 300px;
    background-color: red;
}

.childClass{
    background-color: blue;
    height: 150px;
    width: 150px;
}

/* This is where you define the hover effect */
.parentClass:hover > .childClass {
    background-color: green;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Test</title>
</head>

<body>
    <div class="parentClass">
        <div class="childClass">

        </div>
    </div>
</body>

</html>

Answer №2

Here are some CSS rules that you can utilize:

.main {
  background-color: #ccc;
}

.main:hover {
  background-color: #aaa;
}

.main:hover > div {
  color: red;
  font-weight: bold;
}
<div class="main">
  <div class="num">Number</div>
  <div class="name">Name</div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to comprehend IE comments in a given condition?

I recently came across some conditional comments in a theme I'm working on that dynamically add classes to the html tag depending on the version of Internet Explorer being used. <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" ...

The form yields no response and fails to send any data

Ensuring that the form on this site successfully sends the name and phone number is crucial. However, upon clicking the send button, I encounter an empty modal window instead of a response indicating whether the data was sent or not. The contents of the fi ...

Unable to transfer card from the top position in the screen

Utilizing Tailwind (flowbite) for the frontend of my project, I encountered an issue where the Navbar was overlapping the Card. I attempted using mt-8 to resolve the problem, but it did not yield significant changes. What adjustments should I make to achi ...

The issue of NextJS React Context API not properly updating values even when implementing useState() functionality

In my NextJS web app, I have implemented a React Context API to persist a value across the application. While I am aware that I can utilize the Consumer tag within the Provider tag to update the value like this: <ProfileContext.Provider> <Prof ...

Instructions for utilizing Express.js to distribute Next.js static site generation files

After running the next export command, a new folder named build is automatically created. I am currently looking to use Express.js to serve these static files. Below is the code snippet: app.use('/', express.static(path.join(__dirnam ...

JavaScript Tab Fade Effect

I have a tab system that utilizes JavaScript to switch tabs. I am trying to implement a fade in and out effect when switching tabs. The current JavaScript simply adds or removes the clicked tab selected by the user. I have managed to partially achieve the ...

Tips for positioning Material Ui buttons beside a list of images

I have a list of images and I would like to display buttons beneath each image Here is my current code: export const Media = (stuff) => { const { medias } = stuff; console.log(medias); const classes = useStyles(); return ( <div classNam ...

In order to resolve the issue in nextjs 13 where the argument is of type 'any[] | null' and cannot be assigned to the parameter of type 'SetStateAction<never[]>', a potential solution may involve explicitly checking for null values

My current project uses Next.js 13 and is based on the Supabase database. I am attempting to fetch data from Supabase and assign it to a variable using useState, but encountering the following error: Argument of type 'any[] | null' is not assigna ...

Adjust the width of content within a wrapper using HTML and CSS to automatically resize

I am facing an issue with a content div that has variable length content arranged horizontally. I want the width of this content div to adjust automatically based on the length of its content. Removing the arbitrary "20%" value from the width property is c ...

Is it possible for me to intercept the NextJs compile process?

As a React developer, I am constantly brainstorming ways to enhance my productivity by utilizing static analysis of component files. My goal is to implement a script that can automatically generate code within component files based on specific characters f ...

Styling CSS Based on Input from Child Siblings

Is it possible to customize an adjacent element based on a valid input from a child element? Let's say we have the following HTML structure: <div id="source"> <input type="text"> </div> <div id="target"> </div> Below ...

When reloading the page, the nextJS SSR useRouter() functionality may not function as expected

I've implemented nextJS SSR in my project and encountered an issue. When attempting to fetch page parameters using the code below, it returns undefined: function About() { const router = useRouter(); const { plan_id } = router.query; console.lo ...

Encountering a Next.js error when attempting to execute code on a live server

Encountering a frustrating error: Failed to compile ./utils/styles.js Error: failed to process internal error: entered unreachable code: assign property in object literal is invalid This annoying error popped up during the build process and can only be res ...

The latest update of NextJS, version 13.1.4, encounters issues when implementing SCSS support with the error message "Module next/dist/compiled/sass-loader/fibers.js not

After setting up a new NextJS project, I decided to incorporate SCSS support. The guidelines provided in the documentation seemed straightforward. Following the installation instructions and including an import of SCSS as shown below: import "@/styles ...

Vertical spacing on elements utilizing a position of absolute

Looking to create vertical space for elements with position:absolute and changing heights using just CSS. Any clever techniques involving containers or display properties that could be helpful? ...

The offcanvas menu in the NextJS Tailwind website does not handle hover or tap events properly when outside of the parent dimensions

My header includes an off-canvas menu that slides in from the right side. Everything seems to be working fine, except for one issue: when the menu is open and visible, the mouse and touch events pass through it to the content underneath. Check out the cod ...

Having trouble aligning two divs on the same line and adjusting the controls to expand their width when there is extra space

I am currently creating an application using React and Material UI, incorporating the autocomplete control feature. Take a look at the code sandbox I have set up. Here are some concerns: I am aiming to have two autocomplete controls displayed on the same ...

Parallax Effect Slows Down When Scrolling In Web Page

Currently in the process of creating a website with a scrolling parallax effect using Stellar.js on the header and three other sections. However, I'm experiencing lag when scrolling, especially at the top of the page. I've attempted to reduce la ...

Ways to append each list item from one unordered list to the end of another based on their unique styles

I am in the process of making a website responsive and I am faced with the task of combining two different menus. In order to achieve this, I need to transfer all list items (li) from one unordered list (ul) to another. Provided below is a simplified vers ...

"Encountering an issue with the Foreach function in nextjs when iterating through

I attempted to iterate through each character in a String, but the SPANS are not displaying. What could I be doing incorrectly? export default function Work() { const logoText = "The future starts here."; return ( <div className=& ...