Search code examples
htmlcsspositiondisplay

Why does this absolute ul move out of its parent?


Why does the ul element get the full width of the wrapper element when the container div is its parent? And how can I change this?

Structure of the HTML:

Wrapper
  | container
       | label
       | input
       | ul
       | botton

HTML & CSS:

.wrapper{
  margin: 20px auto;
}
.container {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 200px;
  width: 80%;
  margin: auto;
}
  
.country-input {
  height: 30px;
  margin-bottom: 50px;
}
  
ul {
  height: 200px;
  width: 100%;
  overflow: hidden;
  overflow-y: scroll;
  position: absolute;
  background-color: #F2F2F2;
  top: 20px;
  left: 0px;
}

 
<div class="wrapper">
  <div class="container">
    <label for="country">State</label>
    <input class="input country-input" id="country" type="text" />
    <ul id='country-list'>
      <li id="US">United States</li>
      <li id="AF">Afghanistan</li>
      <li id="AX">Åland Islands</li>
      <li id="AL">Albania</li>
    </ul>
    <button>explore</button>
  </div>
</div>

Here is a link to the full code

This is how it looks:

here

On the left you can see the negative position the element gets:

here


Solution

  • Its just because your <ul> tag is using padding. Look at snippet and tell me is that what you're looking for?

    .wrapper{
        margin: 20px auto;
    }
    .container {
        position: relative;
        display: flex;
        flex-direction: column;
        height: 200px;
        width: 80%;
        margin: auto
      }
      
      .country-input {
        height: 30px;
        margin-bottom: 50px;
      }
      
      ul {
        height: 200px;
        width: 100%;
        overflow: hidden;
        overflow-y: scroll;
        position: absolute;
        background-color: #F2F2F2;
        top: 20px;
        padding: 0;
      }
    
      li {
        padding-left: 40px;  
    
      }
    <div class="wrapper">
            <div class="container">
                <label for="country">State</label>
                <input class="input country-input" id="country" type="text" />
                <ul id='country-list'>
                    <li id="US">United States</li>
                    <li id="AF">Afghanistan</li>
                    <li id="AX">Åland Islands</li>
                    <li id="AL">Albania</li>
                </ul>
                <button>explore</button>
            </div>
        </div>