【问题标题】:Trying to make a div appear on hover using absolute position. Need help centering it尝试使用绝对位置使 div 出现在悬停时。需要帮助使其居中
【发布时间】:2015-10-11 19:14:01
【问题描述】:

正如标题所示,我正在尝试让 div 出现在锚点的悬停上。我正在使用伪元素在 div 上方显示一个“三角形”。

这里不贴代码,

link to it

这是 HTML:

<ul>
    <li class="menu__item has-sub">
        <a href="javascript:void(0);">Parent</a>
        <ul class="menu menu__sub">
            <li class="menu__item"><a href="javascript:void(0);">item 1 child 1</a></li>
            <li class="menu__item"><a href="javascript:void(0);">item 1 child 2</a></li>
            <li class="menu__item"><a href="javascript:void(0);">item 1 child 3</a></li>
            <li class="menu__item"><a href="javascript:void(0);">item 1 child 4</a></li>
            <li class="menu__item"><a href="javascript:void(0);">item 1 child 4</a>/li>
    </ul>
</li>
</ul>

对不起,我正在使用 sass 的所有 css,所以只是将它反编译成 css。

我的问题是我无法让容器始终以父项为中心,因为我使用的是绝对定位和右/左 hack 来定位它。

我不知道如何正确地做到这一点,所以如果有人能帮助我,我会爱你很久!

另外,如果您需要我清理 css,我会尝试它是 81 行,但我想展示完整的图片。

  • 为澄清而编辑:我需要框始终位于父文本(在本例中为父文本)的中心,但如果父文本更改为 asdfasdfasdf,我需要将框也居中。

基本上,无论父文本或内容如何,​​框都必须始终居中绘制

即:

                  Some Long Text Here
                   -------^-------
                   |   Content   |
                   |   Content   |
                   |   Content   |
                   ---------------

                       Text
               ----------^-----------
               |   Longer Content   |
               |   Longer Content   |
               |   Longer Content   |
               ----------------------

【问题讨论】:

  • 您需要将列表或三角形居中吗?
  • @Gust 需要将整个框居中,三角形应该始终位于 div 的顶部中心,将在帖子中说明
  • 如果文本较长,@Nenad 仍然会中断
  • 抱歉,如果我要重新标记你 @GustvandeWal 无法编辑最后一条评论

标签: html css position dropdown


【解决方案1】:

为父项添加宽度

.menu__item > a {
    color: black;
    display: block;
    font-style: normal;
    font-weight: normal;
    line-height: 3;
    text-transform: uppercase;
    text-align: center; /* add this */
    width: 165px; /* And this (this width should be same as .menu__sub class' width)*/
}

移除right属性并添加0 padding left和margin

.menu__sub {
    background-color: white;
    max-height: 100px;
    overflow: hidden;
    position: absolute;
    text-align: center;
 /* remove right */
    width: 165px;
    padding-left: 0; /* Add this */
    margin: 0 auto; /* and this */
}

【讨论】:

    【解决方案2】:

    在您的 .menu__item 类中,您只需删除 display: inline-block 并添加 text-align: center;

    在您的.menu-sub 中,您需要将左侧和右侧都设置为零left: 0; right: 0; 并添加text-align: center 使其居中;

    JsFiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      相关资源
      最近更新 更多