无论宽度为

时间:2016-07-16 22:42:01

标签: javascript jquery html css

我正在尝试将父级div下方的绝对定位下拉菜单居中,宽度未知。我试图使用margin-left,left和transform而没有运气。

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;
}

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

$("#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();
});

演示: https://jsfiddle.net/iRbouh/ataamc72/