Absolute positioning an element causes element to

2019-08-31 08:25发布

问题:

I have a list that I'd like the main elements to align vertically and the sub elements of each to drop down underneath the main element. I want to keep the position: absolute on the subNav class because the width of this nav will vary from each so I can't set a width. This works in Firefox, but in IE 7 the absolute causes the subnav to display inline (so shifted to the right and up from where I would like). How can I fix this?

Example:

<style>
#nav ul, #nav li ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}
#nav li {
    float: left;    
    width: 120px;
    border-right: 1px solid #000;
    padding: 10px;
}
#nav li ul li {
    float: none;    
    width: auto;
    height: auto;
    border-right: none;
    text-align: left;
    padding: 0; 
}

#nav .subNav {  
    background: #eee;   
    position: absolute;
    padding: 10px;
}
</style>
</head>

<body>
<div id="nav">
    <ul>
    <li>Main One                
            <ul class="subNav">
        <li>Sub One A</li>
        <li>Sub One B</li>
        </ul>           
    </li>
    <li>Main Two    
        <ul class="subNav">
        <li>Sub Two A</li>
        <li>Sub Two B</li>
        </ul>
    </li>
    </ul>
</div>
</body>

回答1:

Don't forget to put in your top and left values.

nav .subNav{
    top:10px;
    left:20px;
}

nav.containerDiv {
     position:relative;
}

HTML

<ul class="nav">
   <li>
      <div class="containerDiv">
         <ul class="subNav">...
      </div>
   </li>
</ul>

This will result in the subNav being relative to the container div, instead of the whole document.