Jason Kelly
Jason Kelly

Reputation: 2655

li hover spills out past the ul box

Why would (on hover) the below, spills out onto past the UL box?

Shouldn't it have a 3px border all around to prevent such happening?

enter image description here

Here's the markup

<!DOCTYPE html>

<html>

<head>

<style type="text/css">
#container {
    width: 200px;
    float: left;
    font-family: Arial;
    font-size: 10pt;
}
#one {
    height: 200px;
    border: 1px solid red;
    display: none
}
#two {
    width: 8px;
    height: 8px;
    border: 1px solid blue;
    float: left;
}
#menu, ul {
    list-style: none;
    padding: 3px;
    margin: 0;
    cursor: default;
    width: 200px;
}
#menu, ul, li {
    padding: 3px;
}
#menu li:hover{
    background: blue;
    color: #fff;
}
</style>

<script type="text/javascript">
 function showMenu(){
   document.getElementById("one").style.display="block";
 }
 function hideMenu(){
   document.getElementById("one").style.display="none";
 }
</script>

</head>

<body>

<div id="container">
    <div id="one" onclick="hideMenu()">
        <ul id="menu">
          <li>Item 1</li>
          <li>Item 2</li>
        </ul>
    </div>
</div>

<div id="two"><img src="images/arrow_double.png" onclick="showMenu()"></div>
</body>

</html>

Upvotes: 1

Views: 321

Answers (4)

Becuzz
Becuzz

Reputation: 6864

Your div (#container) has a width of 200px and 3px of padding. Your ul is also 200px wide. With the padding from the div, the ul spills out of the div. This is why when you hover the li it goes outside the div box.

Upvotes: 2

DaniP
DaniP

Reputation: 38252

Your main container has width:200px :

#container {
   width: 200px;
}

Then inside you're setting an object with width:200px and padding:3px it's equal to 206px total width:

#menu, ul {
  padding: 3px;
  width: 200px;
}

You have two solutions:

  • One use this property : That makes all border and padding values to be inside the fixed width.

     #menu, ul {
       box-sizing:border-box;
     }
    
  • Two fix your width:

      #menu, ul {
        width:194px; /*200 - padding for both sides*/
        padding:3px; 
     }
    

Upvotes: 3

K.A.F.
K.A.F.

Reputation: 2337

Your container is 200px wide. The menu is 200px wide + 6px padding (3 for each side). Set the menu size to 194px wide or remove the menu width entirely.

Upvotes: 0

Michał Wilk
Michał Wilk

Reputation: 32

It's because ul padding:3px Set it to 0 or change box-sizing

Upvotes: 0

Related Questions