首页 > 解决方案 > flex 容器中的 ul 项目在悬停时移动

问题描述

我正在使用 bootstrap 4 和字体真棒图标。

我正在尝试创建一个带有动画的侧导航栏。每当我将鼠标悬停在 ul 项目上时。它下方的所有项目都向上移动,将悬停的项目隐藏在其下方。

如何防止这种行为?

<style type="text/css">
        .sidenav .container {
            position: fixed;
            overflow-x: visible;
            max-width: 50px;
            top: 15%;
            max-height: 70%;
            justify-content: left;
            padding-left: 0;
            z-index: 1;
        }

        .nav-item .btn {
            color: lightgray;
            width: 100%;
            background-color: #343a40;
            border-bottom: #0c0c0c solid;
            border-radius: 0 10px 10px 0;
            transition: color 400ms, width 400ms;
        }

        .sidenav .btn:focus {
            box-shadow: none !important;
        }

        .nav-item:hover > .btn:hover {
            background-color: lightgray;
            color: #343a40;
            width: 75px;
            position: absolute;
        }
</style>
<div class="sidenav">
        <div class="container">
            <ul class="nav flex-column">
                <li class="nav-item">
                    <button class="btn" data-toggle="modal" data-target="#notebookModal"><i
                            class="fas fa-clipboard-list fa-2x"></i></button>
                </li>
                <li class="nav-item">
                    <button class="btn" data-toggle="modal" data-target="#addNoteModal"><i
                            class="fas fa-plus-circle fa-2x"></i></button>
                </li>
            </ul>
        </div>
    </div>

标签: htmlcssbootstrap-4font-awesome

解决方案


为了防止它们向上移动,请position: absolute从悬停类中删除:

.nav-item > .btn:hover {
    background-color: lightgray;
    color: #343a40;
    width: 75px;
}

编辑添加:

将鼠标悬停在一个按钮上会影响其他按钮的宽度,因为宽度设置为 100%。要解决此问题,请将非悬停按钮更改为 100% 以外的值(因为其他非悬停按钮变为 100% 宽,这会随着悬停时的过渡而变化)。

您可以选择值,width: 55px;例如,或者根据引导.btn填充计算它,当我检查元素时,它是 0.75rem 的左填充。您为 sidenav 容器提供了 50px 的宽度和 0 的左侧填充,因此您可以使用它calc()来确定如果 rem 值发生变化时 100% 是多少:

.nav-item > .btn {
  color: lightgray;
  width: calc(50px + .75rem);
  background-color: #343a40;
  border-bottom: #0c0c0c solid;
  border-radius: 0 10px 10px 0;
  transition: color 400ms, width 400ms;
}

推荐阅读