user5613506 user5613506 - 2 months ago 21
CSS Question

Expand list-item background-color on :hover of Bootstrap Dropdown

Maybe the title doesn't represent what I want to know, but in any case, here's a demo

Hovering the single element opens a dropdown menu. When hovering each item, a very distinguishable

background-color
is applied.

What i would like to accomplish is, when hovering the first or last items to extend the
background-color
to cover that white(ish) rounded border

I tried to add:

.nav li ul li a:first-child:hover {
margin-top: -5px;
padding-top: 10px;
padding-bottom: 10px;
}


Without much pretension to get it working (so I didn't adjust much the values) and I more or less achieved my goal, at expense of losing the rounded border

Of course, i could dig the Bootstrap CSS and find the exact values of the rounded border and reapply them here, but in overall the code seemed wrong to me.

Am I on right track to solve or is there a better way?

Answer

Use this:

.dropdown-menu {
    padding: 0 !important;
}
.nav li ul li:first-child a {
 border-radius: 4px 4px 0 0;
}
.nav li ul li:last-child a {
    border-radius: 0 0 4px 4px;
}

body {
    background-color: blue;
    padding: 100px;
}

.nav {
  background-color: #EDEDED;
  width: 200px;
}

    .nav li ul li a:hover {
        background-color: red;
        color: #FFF; 
     }
    
    .nav ul li a {
      padding: 10px 15px;
    }
.dropdown-menu {
  padding: 0 !important;
}
      
.dropdown-menu .sub-menu {
    left: 100%;
    position: absolute;
    top: 0;
    visibility: hidden;
    margin-top: -1px;
}

.dropdown-menu li:hover .sub-menu {
    visibility: visible;
}

.dropdown:hover .dropdown-menu {
    display: block;
    top: -10px;
    margin-right: -25%;
}
.nav li ul li:first-child a {
    border-radius: 4px 4px 0 0;
}
.nav li ul li:last-child a {
    border-radius: 0 0 4px 4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<ul class="nav">

    <li class="dropdown" id="collection">
        <a class="dropdown-toggle" data-toggle="dropdown" href="#">
            <span class="fa fa-bars"></span>
            Items
        </a>

        <ul class="dropdown-menu dropdown-menu-right sub-menu">
            <li>
                <a href="#">Item</a>
            </li>
            <li>
                <a href="#">Item</a>
            </li>
            <li>
                <a href="#">Item</a>
            </li>
            <li>
                <a href="#">Item</a>
            </li>
        </ul>
    </li>
</ul>