简体   繁体   中英

How to center horizontally a div within an li in CSS

I have a very simple drop down menu, like so:

<ul class="nav multilevel">
    <li><a href="#">item 1</a></li>
    <li><a href="#">item 2</a></li>
    <li><span>item 3 +</span>
        <div class="cntLevel level">
            <ul>
                <li><a href="#">short item 1</a></li>
                <li><a href="#">very long menu item 2</a></li>
                <li><a href="#">medium menu item</a></li>
            </ul>
        </div>
    </li>
</ul>

with the following CSS:

ul {margin:0; padding: 0; list-style: none;}

.nav {
    background-color: #aaa;
    text-align: center;
}

.nav > li {
    position: relative;
    display: inline-block;
    padding: 30px;
}

.nav > li:hover {
    background-color: #ececec;
}

.nav > li > a, .nav > li > span {
    font-size: 20px; color: #333; text-decoration: none;
    cursor: pointer;
}

.multilevel .cntLevel {
    display: block;
    position: absolute;
    right: 0; top: 83px;
    z-index: 100;
}

.cntLevel {
    padding: 5px 0;
    background-color: rgba(40, 40, 40, 1);
}

.level li {
    white-space: nowrap;
}

.level li a {
    display: block;
    padding: 5px 20px;
    color: #a6a6a6;
    text-align: left; text-decoration: none;
}

.level li a:hover {
    color: red;
}

All works perfectly! Here's the jsfiddle as prove:

https://jsfiddle.net/jq2ub0jr/1/

So, what's the problem. Here it is:

I want to center the submenu (drop down menu) to the <li> (list item). Right now, it's right aligned. I can probably achive it by declaring a fixed width and a negative margin-left width a left property. But, i definitely don't want to add a fixed width.

How to center my drop down submenu with the <li> ?

Thanks

Your container ( li ) is relatively positioned.

Your submenu div (child of li ) is absolutely positioned.

To center the submenu all you need to do is add...

left: 50%;
transform: translate(-50%, 0);

... to the submenu div .

Then you need a width. But you don't want a fixed width. So add a minimum width:

min-width: 200px;

So the style rule becomes:

.multilevel .cntLevel {
    display: block;
    position: absolute;
    /* right: 0; remove this */
    top: 83px;
    z-index: 100;

    /* NEW */
    left: 50%;
    transform: translate(-50%, 0);
    min-width: 200px;
    }

The submenu is now centered and will expand with longer text.

Demo: https://jsfiddle.net/jq2ub0jr/6/

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