2016-10-10 38 views
0

我有一个粘性的主菜单与选项卡“类别”下拉菜单“categoriesDropdown”,当我将鼠标悬停在它上面。我如何中心div到身体不是它的父母

  • 我需要下拉菜单具有屏幕的宽度,并且是 在屏幕的中心。

  • 我需要下拉菜单来粘贴到主菜单的底部。

唯一的问题是,我似乎无法将下拉菜单居中。我只能把它放在相对于父div(类别) 我使用的代码显示在下面。

<div class="categories"> 
    <a>Categories</a> 
    <div id="categoriesDropdown"></div> 
</div> 

CSS

.categories { 
    padding-left: 20px; 
    padding-right: 20px; 
    height: 45px; 
    display: inline-block; 
    box-sizing: border-box; 
    -moz-box-sizing: border-box; 
    -webkit-box-sizing: border-box; 
} 

#categoriesDropdown { 
    position: absolute; 
    background: #1d1d1d; 
    width: 100vw; 
    height: 0px; 
    z-index: -1; 
    overflow: auto; 
} 

#categoriesDropdown.show { 
    height: 500px; 
} 

编辑:发生这种情况时,我尝试左:0;正确:0; the grey square being the drop down menu

+0

如果我理解正确的你应该做的就是把左:0,右:0在您的#categories下降到cen如果需要,可以使用顶部:0和底部:0垂直居中如果需要 – Benneb10

+0

将它居中在类别div的中间。我的问题是我如何将它集中在身体中央。 – hermanboy07

回答

0

只用CSS就很棘手,但这里有jQuery和css可能的解决方案。我不确定这会对你有没有帮助。

身体

<div class="categories"> 
    <a>Categories</a> 
    <div id="categoriesDropdown" class="categoriesDropdown"> </div> 

的CSS

body{ 
    margin : 0px; 
    padding : 0px; 
    } 
    .categories { 
    padding-left: 20px; 
    padding-right: 20px; 
    height: 20px; 
    display: inline-block; 
    box-sizing: border-box; 
    -moz-box-sizing: border-box; 
    -webkit-box-sizing: border-box; 
    cursor : pointer; 
    top: 50px; 
    position: absolute; 
    } 
    .categoriesDropdown { 
    position: relative; 
    background: #1d1d1d; 
    width: 98vw; 
    height: 0px; 
    z-index:-1; 
    overflow:auto; 
    margin:0 auto; 
    color:#fff; 
    } 
    .categoriesDropdown_show { 
    height: 100px; 
    } 

脚本

$(document).ready(function(){ 

    var c = $(".categories"); 
    var position = c.position(); 

    $(".categories").mouseenter(function(){ 
     $("#categoriesDropdown").appendTo('body'); 
     $(".categoriesDropdown").addClass("categoriesDropdown_show"); 
     $('#categoriesDropdown').css({'top':'calc('+position.top +'px + 20px)'}); 
    }); 
    $(".categories").mouseleave(function(){ 
     $(".categoriesDropdown").removeClass("categoriesDropdown_show"); 
     $("#categoriesDropdown").appendTo('categories'); 
    }); 
    }); 
+0

您也可以声明类'categories'而不是'20px'高度的var。 //$('#categoriesDropdown').css({'top':'calc('+position.top +'px + 20px)'}); var h = c.height(); ('#categoriesDropdown')。css({'top':'calc('+ position.top +'px +'+ h +'px)'}); – kish0022