简体   繁体   中英

How do I make a parent div the height of its children?

This seems like a really stupid question, but I can't figure it out.

I've got an UL styled into a horizontal menu, but the parent div won't adjust to the height of the child elements. Here's a jsFiddle: http://jsfiddle.net/STSjm/202/

HTML

<div class="menu">
<ul>
    <li><a href="#">Menu 1</a></li>
    <li><a href="#">Menu 2</a></li>
    <li><a href="#">Menu 3</a></li>
</ul>
<div class="clear"></div>

And the CSS:

.menu {
    background: blue;
}

.menu li{
    float: left;
    background: green;
}

.menu li a{
    background: red;
    padding: 25px 25px 25px 25px;
}

.menu li a:hover{
    background: orange;
}

.clear {
    clear: both;
}

Here's what's going on:

Your <a> elements have padding, but they are display:inline by default which adds padding outside the element, while not actually adding width/height to it, which is why the menu isn't expanding.

To fix this, set display:block to the anchors:

http://jsfiddle.net/STSjm/216/

In addition, you don't need the "clear" div, adding this CSS should do the trick:

.menu {
    float:left;
    width:100%;
}

http://jsfiddle.net/STSjm/218/

There are also a number of CSS only "clearfix" tricks to solve this without adding extra unnecessary HTML markup.

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