在 Wordpress 中设置下拉菜单样式的问题

Problems with styling the dropdown-menu in Wordpress

在 Wordpress 中,我正在尝试设置 .primary-menu 中使用的下拉菜单的样式。不幸的是,事情并没有真正按计划进行。

我从 Chrome 中的检查器复制了 HTML 并删除了诸如 href 和 id 之类的混乱,并尝试在 jsFiddle 中对其进行调试:https://jsfiddle.net/1cL8fq8b/1/

将鼠标悬停在结果选项卡中的最后一个 item 上时,.sub-item 似乎占据了其父项的宽度。我给了.sub-menu一个绝对的位置让它独立。我仍然无法让 .sub-item 拥有自己的宽度。 Here's a screenshot for a better view

我怎样才能让子项目有自己的宽度,而不依赖于它的父项的宽度?

这是因为悬停时它的 display 设置为 block。将其设置为 inline-block 而不是

首先也是最重要的是..阅读这篇文章http://learnlayout.com/position.html

absolute is the trickiest position value. absolute behaves like fixed except relative to the nearest positioned ancestor instead of relative to the viewport. If an absolutely-positioned element has no positioned ancestors, it uses the document body, and still moves along with page scrolling. Remember, a "positioned" element is one whose position is anything except static.

所以基本上绝对定位只是将其从文档流中取出

还有..这段代码..

&:hover .sub-menu

仅针对子菜单。尝试定位子菜单的 li 以赋予它自己的宽度。子菜单 ul(这是您的定位与 li 的宽度无关的内容,除非它们是根据百分比调整大小的。

您可以添加负 margin-left 样式以将下拉菜单向左扩展。

.sub-menu {
        position: absolute;
        right: 0;
        display: none;
        margin-left:-100px;
}

看到这个:https://jsfiddle.net/jokbd6L5/

或者为您的下拉菜单定义自定义宽度:

.sub-menu {
        position: absolute;
        right: 0;
        display: none;
        width:100px;
}

看到这个:https://jsfiddle.net/hjoctv5x/

因为它的位置是绝对的,所以我认为 CSS 没有办法让它根据内容的宽度(可变宽度)展开。但是你可以写一些 javascript 来计算每个下拉菜单的最大内容宽度,并相应地设置下拉菜单宽度。