Search code examples
htmlcssnavigationalignmentdropdown

How do I vertically align a div so the backgrounds are perfectly matched and the text is in the center?


The HTML is below and it is for a drop down box:

<div class="dropdown">
    <h1>Dropdown Box</h1>
    <ul>
        <li><a href="#">List Item</a></li>
        <li><a href="#">List Item</a></li>
        <li><a href="#">List Item</a></li>
    </ul>
</div>

CSS is below, I have tried vertical align everywhere and can't seem to figure it out. The background of the nav button and the drop down are out of line.

.dropdown {
    position: absolute;
}

.dropdown h1 {
    background-color: #62dbfc;
    font-family: "calibri light";
    padding: 15px 35px;
    margin: 0 auto;
}

.dropdown ul {
    margin: 0 auto;
    position: absolute;
    width: 100%;
}

.dropdown li {
    list-style-type: none;
    background-color: #ededed;
    margin: 0 auto;
    font-family: calibri;
    font-size: 24px;
    text-align: center;
    position: relative; 
}

Solution

  • I think what you want is to add padding-left: 0 to the .dropdown ul styling. Here is a working example using your code:

    .dropdown { 
        position: absolute;
    }
    
    .dropdown h1 {
        background-color: #62dbfc;
        font-family: "calibri light";
        padding: 15px 35px;
        margin: 0 auto;
    }
    
    .dropdown ul {
        margin: 0 auto;
        position: absolute;
        width: 100%;
        padding-left: 0;
    }
    
    .dropdown li {
        list-style-type: none;
        background-color: #ededed;
        margin: 0 auto;
        font-family: calibri;
        font-size: 24px;
        text-align: center;
        position: relative;
    
    }
    <div class="dropdown">
        <h1>Dropdown Box</h1>
        <ul>
            <li><a href="#">List Item</a></li>
            <li><a href="#">List Item</a></li>
            <li><a href="#">List Item</a></li>
        </ul>
    </div>