html - 可以 float 在任意后续内容上的简单 CSS 菜单

标签 html css menu hover css-float

我想要一个只使用 CSS,不使用 JavaScript 的简洁的解决方案。 我最感兴趣的是这是否/如何需要 z-index <menu> 上的设置和其他元素,如果有不需要 z-index 的干净解决方案设置,特别是不在“内容”标签上。当然,当菜单打开时,菜单后面的内容不应该改变位置。

所需的(示例性)html 结构:

<menu>
  <ul>
    <li>Item 1
    <li>Item 2
    <li>BigItm3
    <li>Item 4
    <li>Item 5
    <li>LastItm
  </ul>
</menu>
<p>Text</p>
<p>MoreText</p>
<p style="float:left">Floating</p>
<img style="position:absolute; left:100px; top: 40px;"
     src="http://tinyurl.com/jaheira-dance">
<form><button>OK</button><br><textarea>text</textarea></form>
<p>HTML content (e.g., loaded + injected via ajax)</p>
<iframe>

期望的视觉行为:1. 当鼠标悬停在菜单上时

  --------
  | Menu |
  --------
Lorem ipsum dolor
sit amet    ==========
===== Lorem | iframe |
|img| ipsum |        |
===== dolor ==========

期望的视觉行为:2. 当悬停在菜单上时

  -------------
  | Menu      |
  |           |
Lo| * Item 1  |or
si| * Item 2  |=======
==| * BigItm3 |frame |
|i| * Item 4  |      |
==| * Item 5  |=======
  | * LastItm |
  =============

我已经拥有的:

menu:before { content: "Menu"; } /* always display the menu title */

menu {
    float:   left;
    height:  16px;
    padding: 1px;
    margin:  0px;
    font-height: 10px;
    margin-left: 20px;
    border: solid 1px gray;
}

menu>ul       { display: none; }  /* hide menu items when closed */
menu:hover>ul { display: block; } /* show items when open */

menu:hover    {
    height:   auto;  /* expand menu */
    position: fixed; /* move other elements behind menu */
}

menu + * { clear: both; } /* move following content below menu */

最佳答案

这就是您需要更改的全部内容。

If your cat image doesn't need to be position absolute

menu {
  position: absolute; /* Change */
  top: 0; /* Change */
  left: 20px; /* Change */
  background: #fff; /* Change (not needed but without a bg the text will show through */
  height:  16px;
  padding: 1px;
  margin:  0px;
  font-height: 10px;
  border: solid 1px gray;
}

If it does need to be absolute then you can use an z-index

menu {
  position: absolute;
  top: 0;
  left: 20px;
  background: #fff;
  height:  16px;
  padding: 1px;
  margin:  0px;
  font-height: 10px;
  border: solid 1px gray;
  z-index: 10;
}

I am most interested if/how this requires z-index settings on the

它需要 z-index 的原因是图像具有绝对位置,它将这两个元素放在同一水平面上。

如果您对 z-index 有意见,那么您可以允许元素进入页面的顺序来决定哪些元素堆叠在哪些元素之上。通过将菜单添加到 HTML 的末尾,您将在没有 z-index 的情况下获得所需的结果,因为它堆叠在另一个 absolute 对象之上。

Without z-index

关于html - 可以 float 在任意后续内容上的简单 CSS 菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19549420/

相关文章:

menu - 编辑右上角菜单 Odoo v8

php - 只想使用 PHPExcel 从 excel 文件打印单元格数据?

javascript - 在 jquery 对话框中将 <li> 值附加到 <ul> 不起作用

html - 使用 CSS Flexbox 旋转 HTML 文本输入

javascript - 无法展开和折叠子行

qt - 如何在Qt中动态添加菜单

javascript - 未捕获的ReferenceError : require is not defined - Electron js

javascript - 如何制作 OR 选择器而不是 AND 语句

html - CSS - 使 3x3 图形适合在 div 内平铺/缩放?

android - 设置抽屉导航图标的背景