1

I have css and html codes as below.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

ul {
  list-style-type: none;
}

.container {
  width: 1000px;
  margin: 0 auto;
}

.top-content {
  width: 100%;
  height: 100px;
  background-color: gray;
}

nav ul {
  display: flex;
  justify-content: space-around;
}

nav ul li:hover {
  cursor: pointer;
  color: red;
}

main {
  width: 100%;
  height: 500px;
  background: green;
}

nav ul li:hover .top-content {
  background: red;
}

nav ul li:hover main {
  background: red;
}
<div class="container">
  <div class="top-content"></div>

  <nav>
    <ul>
      <li>Lorem</li>
      <li>Lorem</li>
      <li>Lorem</li>
      <li>Lorem</li>
      <li>Lorem</li>
    </ul>
  </nav>

  <main></main>
</div>

What I want is for the .top-content class and main element to be colored red when I hover over the li elements. But as far as I understand, I'm having a problem with the selectors. How can I change the color of these elements using css only?

Pan Vi
  • 627
  • 6
  • 17
ardaberrun
  • 11
  • 3

1 Answers1

2

CSS properties cannot modify anything but elements and their children (they cannot access parents or siblings). More info here.

You need to take aid of JavaScript, to achieve this.

let lis = document.querySelectorAll("nav ul li");
let topContent = document.querySelector(".top-content"); 

let main = document.querySelector("main"); 

lis.forEach(li=>{
  li.onmouseover = ()=>{
    topContent.style.background = "red";
    main.style.background = "red";
  }
  li.onmouseleave = ()=>{
    topContent.style.background = "gray";
    main.style.background = "green";
  }
  
})
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

ul {
  list-style-type: none;
}

.container {
  width: 1000px;
  margin: 0 auto;
}

.top-content {
  width: 100%;
  height: 100px;
  background-color: gray;
}

nav ul {
  display: flex;
  justify-content: space-around;
}

nav ul li:hover {
  cursor: pointer;
  color: red;
}

main {
  width: 100%;
  height: 500px;
  background: green;
}
<div class="container">
  <div class="top-content"></div>

  <nav>
    <ul>
      <li>Lorem</li>
      <li>Lorem</li>
      <li>Lorem</li>
      <li>Lorem</li>
      <li>Lorem</li>
    </ul>
  </nav>

  <main></main>
</div>
TechySharnav
  • 4,869
  • 2
  • 11
  • 29
  • Thank you for the answer. Actually, what I wanted to do was to add an overlay to these fields while the li element is in the hover state. I guess i cant, thank you again. – ardaberrun Jul 02 '21 at 08:21
  • Welcome. What kind of overlay you want to add? Just asking. – TechySharnav Jul 02 '21 at 08:36