InQusitive InQusitive - 5 months ago 10
CSS Question

Why is the hover behavior unintuitive in case of ul and li?

I wanted to highlight each menu item with red color while hovering over it. So with my intuition I did

.menu ul li: hover{...}
.

Doubt 1: But this made only the
li
text background change the color and not the padding part of the
li
. Why isn't the
padding
change the color?Isn't the
padding
also a part of
li
element?

Doubt 2: I achieved the expected behavior by doing
.menu ul :hover
as shown in the below code. But this is against my intuition. Doesn't it say the entire
ul
should change the background color while hovering on it, so that the entire menu items will be highlighted?

The Code:



body {
background-color: #EEE;
margin: 0;
padding: 0;
}
.header {
height: 60px;
background-color: #FFF;
box-shadow: 0 0 3px rgba(0,0,0,.2);
}
.logo {
position: relative;
display: inline-block;
height: 40px ;
width: 100px ;
top:10px;
left: 10px;
}
.menu ul {
float: right;
padding: 0;
list-style-type: none;
margin-right:40px;
margin-top: auto;
margin-bottom:auto;
}
.menu ul li {
position: relative;
top: -15px;
display: inline;
padding:10px 20px;
}
.menu ul :hover {
background-color: red;
}
.menu ul li a {
text-decoration: none;
}

<div class="header">
<div class="logo">
<img src="logo_new1.png" class="img">
</div>
<div class="menu">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Activities</a></li>
<li><a href="#">About us</a></li>
<li><a href="#">Contacts</a></li>
</ul>
</div>
</div>




Answer

At the moment, you are not hovering the ul because you have a space between the ul and :hover so it is adding background:red to all children elements of ul( which are li) when hovered. That's why you think you it is working with ul,

This is the real output of your code

.menu ul *:hover {background:red}

The :hover it will affect the padding if that element has padding if not, it won't add padding, so if you want to have padding you have to :hover the li

body {
  background-color: #EEE;
  margin: 0;
  padding: 0;
}
.header {
  height: 60px;
  background-color: #FFF;
  box-shadow: 0 0 3px rgba(0, 0, 0, .2);
}
.logo {
  position: relative;
  display: inline-block;
  height: 40px;
  width: 100px;
  top: 10px;
  left: 10px;
}
.menu ul {
  float: right;
  padding: 0;
  list-style-type: none;
  margin-right: 40px;
  margin-top: auto;
  margin-bottom: auto;
}
.menu ul li {
  position: relative;
  top: -15px;
  display: inline;
  padding: 10px 20px;
}

.menu ul li a {
  text-decoration: none;
}
.menu ul li:hover  {
  background-color: red;
}
<div class="header">
  <div class="logo">
    <img src="logo_new1.png" class="img">
  </div>
  <div class="menu">
    <ul>
      <li><a href="#">Home</a>
      </li>
      <li><a href="#">Activities</a>
      </li>
      <li><a href="#">About us</a>
      </li>
      <li><a href="#">Contacts</a>
      </li>
    </ul>
  </div>
</div>