将position的父级:绝对子级扩展为子级的宽度

时间:2013-09-26 11:44:32

标签: html css

http://jsfiddle.net/q8eDF/我试图获得一个菜单样式,但它还不是很完美。

如何为绿色区域(即整个菜单)显示.dropdown-container的红色边框,.dropdown-header的蓝色边框延伸到.dropdown-item的右边框(或者, .dropdown-item扩展到.dropdown-header的边框,以防标题比最宽项目更宽),同时在.dropdown-header的最后一个字符和.dropdown-arrow之间允许~10px的空间?

我不关心BC,只要目前的FF和Chrome可以运行它,我就没事了。

HTML:

<div id="dd" class="dropdown-container">
  <div class="dropdown-header">Feed options<span class="dropdown-arrow">v</span></div>
  <div class="dropdown-items">
    <div class="dropdown-item">Reload</div>
    <div class="dropdown-item">Unsubscribe</div>
    <div class="dropdown-item">Reload from source</div>
  </div>
</div>

CSS:

.dropdown-container {
display: inline-block;
border: 1px solid red;
position: relative;
}
.dropdown-items {
display: block;
position: absolute;
z-index: 999;
background: #fff;
border: 1px solid green;
}
.dropdown-items {
margin: 5px 0px;
}
.dropdown-item {
margin: 3px 6px;
cursor: pointer;
}
.dropdown-header {
border: 1px solid blue;
width: 100%;
cursor: pointer;
}
.dropdown-arrow {
position: absolute;
right: 0;
}

1 个答案:

答案 0 :(得分:1)

如果您正在使用导航栏,我建议将整个物品包装在绝对定位的容器中,以便它可以漂浮在其他内容之上:

<强> HTML

<div class="navbar">
    <div id="dd" class="dropdown-container">
        <div class="dropdown-header">
            Feed options<span class="dropdown-arrow">v</span>
        </div>
        <div class="dropdown-items">
            <div class="dropdown-item">Reload</div>
            <div class="dropdown-item">Unsubscribe</div>
            <div class="dropdown-item">Reload from source</div>
        </div>
    </div>
</div>

<强> CSS

.navbar { 
    position: absolute; 
    top: 0px; 
}
.navbar > div { 
    display: inline-block; 
    vertical-align: top; 
}

body { 
    padding-top: 23px; 
}

.dropdown-container {
    display: inline-block;
}
.dropdown-header {
    width: 100%;
}
.dropdown-arrow {
    float: right;
}

Fiddle