Joe Joe - 4 months ago 8
CSS Question

Centre drop down menu below parent div regardless of width

I'm attempting to centre my absolute drop down menu below the parent div which is of unknown width. I've attempted to use margin-left, left, and transform with no luck.

How it looks versus how I want it to look

JSFiddle

HTML

<div id="heads">
<div class="contain">
<div id="heads-menu">
<div id="heads-menu-name">
<img src="../resources/profile-icon.svg" />
<div>John Smith</div>
</div>
<div id="heads-menu-nav">
<div></div>
<a href="#">View Profile</a>
<a href="#">Options</a>
<a href="#">Help</a>
<a href="#">Close Session</a>
</div>
</div>
</div>
</div>


CSS

#heads-menu {
float: left;
}
#heads-menu-name {
border-bottom: 2px solid transparent;
cursor: pointer;
padding: 22px 0 20px 0;
-webkit-transition: all .5s;
-moz-transition: all .5s;
transition: all .5s;
}
#heads-menu-name img {
-webkit-border-radius: 100%;
-moz-border-radius: 100%;
border-radius: 100%;
float: left;
height: 26px;
margin-right: 10px;
width: 26px;
}
#heads-menu-name div {
color: #666;
float: left;
font: 600 normal normal 12px/16px Source Sans Pro, Arial, Helvetica, sans-serif;
margin: 5px 0;
-webkit-transition: all .5s;
-moz-transition: all .5s;
transition: all .5s;
}
#heads-menu-name:hover {
border-bottom: 2px solid #5098BB;
}
#heads-menu-name:hover div {
color: #5098BB;
}
#heads-menu-nav {
background: rgba(0,0,0,.8);
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
display: none;
overflow: visible;
padding: 5px 0;
position: absolute;
width: 140px;
}
#heads-menu-nav div {
border-bottom: 8px solid rgba(0,0,0,.8);
border-left: 8px solid transparent;
border-right: 8px solid transparent;
height: 0;
margin: 0 62px;
position: absolute;
top: -8px;
width: 0;
}
#heads-menu-nav a {
color: #CCC;
font: 600 normal normal 12px/16px Source Sans Pro, Arial, Helvetica, sans-serif;
padding: 10px 20px;
text-decoration: none;
-webkit-transition: all .5s;
-moz-transition: all .5s;
transition: all .5s;
}
#heads-menu-nav a:hover {
background: rgba(255,255,255,.2);
color: #FFF;
}

Answer

You can try this :

$("#heads-menu-name").click(function(e) {
    var linkWidth = $(this).width();
    $("#heads-menu-nav").css('marginLeft', function() {
        return '-' + (($(this).width()/2)-(linkWidth/2)) + 'px';
    }).toggle();
    e.stopPropagation();
});

Demo: https://jsfiddle.net/iRbouh/ataamc72/

Comments