简体   繁体   中英

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; 
}

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> 

You can try using flexbox. Here's a great example:

https://philipwalton.github.io/solved-by-flexbox/demos/vertical-centering/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM