html - 像容器一样定位绝对元素的宽度(在 css 中)

标签 html css

于是就有了下面的布局:

enter image description here

我们关注“SERVICEUSER”按钮及其子菜单问题。

那么有没有办法让子菜单的最小宽度(绝对位置)与其父菜单相同。

我已经重现了这个情况 jsfiddle link .

所以基本上需要的是使 .collection min-width 与 li 的宽度相同。

这种情况的html结构是这样的:

<ul>
  <li>
    <a href="">SERVICEUSER</a>
    <div class="collection">
      <div class="item">Item-1</div>
      <div class="item">Item-2</div>
      <div class="item">Item-3</div>
    </div>
  </li>
</ul>

这种情况的css是这样的:

ul { list-style-type: none; }

li { display: inline; }

a { background: green; }

.collection {
  position: absolute; // this is necessary for the situation
  background: white;
}

最佳答案

用“absolute”定位的元素包含在其最近的相对父元素的流中。如果你使 li 成为相对的,你可以设置集合的宽度。

li { display: inline; position: relative; }

.collection {
  position: absolute;
  background: white;
  min-width: 100%;
  white-space: nowrap;
}

编辑:我添加了 white-space: nowrap 以允许集合(子项)大于主项。

关于html - 像容器一样定位绝对元素的宽度(在 css 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36347565/

相关文章:

html - IOS 上的占位符文本输入

css - 我希望我的链接只在我点击它时改变颜色,而不是仅仅通过刷新页面。我如何使用 CSS 做到这一点?

css - 在@font-face CSS 规则中正确定义字体系列

html - 海滩背景中间图像垂直重复必须显示全尺寸以匹配底部图像

css - 使用 CSS 缩放图像但限制为原始大小

html - Delphi:解析此 html 表的一些提示?

html - 分区 : Percentage width but does not resize with parent

javascript - 解析表单之外的 ng-model

javascript - for 循环中的 HTML 表 TD 未正确生成

javascript - "Print"数据库中复选框中的值