Search code examples
htmlcsshovercss-grid

Why the li hover is covering only the text part and not the whole li box?


I'm trying to give the hover effect to the li which appears to cover only the text part and not the whole li-box. I wonder why is it happening like this?

*{
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
html, body{
margin: 0;
padding: 0;
}

.container {
display: grid;
background-color: rosybrown;
border: 1px solid black;
justify-items: center;
}
.heading{
order: 2;
}

.main-nav{
order:1;
text-align: center;
width: 100%;
border-bottom: 1px solid rebeccapurple;
padding: .5em;
}

.main-nav ul{
 margin:0;
 }
.main-nav li:hover{
background-color: rgba(255,255,255,0.3);
}

 ul{
 padding: 0;
 }
 .main-nav li{
 display: inline;
 margin: 1em;
    
 }
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<link rel="stylesheet" href="trialStyle.css">
 </head>
 <body>
  <div class="container">
    <h1 class="heading">The Love</h1>
    <nav class="main-nav">
        <ul class="ulContainer">
        <li>Home</li>
        <li>About</li>
        <li>Store</li>
    </ul>
    </nav>
 </div>
</body>
   </html>


Solution

  • The hover effect only covers the text part because that is the size of the rendered li element. If you want the effect over a block, you could use padding instead of margin CSS property:

    Refer the given link of W3 Schools below

    *{
    box-sizing: border-box;
    font-family: Arial, Helvetica, sans-serif;
    }
    
    html, body{
    margin: 0;
    padding: 0;
    }
    
    .container {
    display: grid;
    background-color: rosybrown;
    border: 1px solid black;
    justify-items: center;
    }
    
    .heading{
    order: 2;
    }
    
    .main-nav{
    order:1;
    text-align: center;
    width: 100%;
    border-bottom: 1px solid rebeccapurple;
    padding: .5em;
    }
    
    .main-nav ul{
     margin:0;
     }
    
    .main-nav li:hover{
    background-color: rgba(255,255,255,0.3);
    }
    
     ul{
     padding: 0;
     }
    
     .main-nav li{
     display: inline;
     /*padding: 1em;
     padding-bottom: 0.5em;*/
     padding: .5em;
     }
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <title>Document</title>
    <link rel="stylesheet" href="trialStyle.css">
     </head>
     <body>
      <div class="container">
        <h1 class="heading">The Love</h1>
        <nav class="main-nav">
            <ul class="ulContainer">
            <li>Home</li>
            <li>About</li>
            <li>Store</li>
        </ul>
        </nav>
     </div>
    </body>
       </html>

    CSS Box Model