中心绝对定位儿童元素

时间:2016-09-12 12:29:40

标签: html css

我需要水平居中内联块的子元素。问题是子子菜单的宽度可变,并且可以比其父菜单宽。我最初的解决方案是将子元素设置为左和右。 -50px的权利,但这实际上不是一个可变宽度,而是静态地将其设置为比其父级宽100px。



.main-menu {
    text-align: left;
    margin: 0;
    padding: 0;
    font-size: 0px;
    font-size: 0rem;
}
.main-menu li {
    font-size: 18px;
    font-size: 1.8rem;
    line-height: 1em;
    list-style-type: none;
    text-align: center;
    display: inline-block;
    zoom: 1;
    padding: 0 25px;
    position: relative;
}
li > a {
    display: inline-block;
    zoom: 1;
    padding: 21px 0 19px;
    font-family: "Open Sans", sans-serif;
    font-weight: 400;
    color: #282828;
    font-size: 16px;
    font-size: 1.6rem;
    line-height: 1.2em;
    text-decoration: none;
    -webkit-transition: all .25s ease-in-out, background-image 0s, background-position 0s;
    transition: all .25s ease-in-out, background-image 0s, background-position 0s;
}
.sub-menu {
    position: absolute;
    top: 100%;
    left: -50px;
    right: -50px;
    max-width: 250px;
    margin-left: auto;
    margin-right: auto;
    margin-bottom: 0;
    min-width: 150px;
    background-color: white;
    text-align: left;
    padding: 17px 0;
    box-shadow: 0 2px 5px #dcdcdc inset;
    border-top: 18px solid #ffdd00;
  }

<ul class="main-menu clearfix"><li id="menu-item-657" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children first menu-item-657">
<li id="menu-item-657" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children first menu-item-657"><a href="link">Solutions</a>
<ul class="sub-menu">
	<li id="menu-item-220469" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-220469"><a href="link">Solutions</a></li>
	<li id="menu-item-18009" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-18009"><a href="link">How It Works</a></li>
	<li id="menu-item-10344" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-10344"><a href="link">Why Use It</a></li>
	<li id="menu-item-3375" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-3375"><a href="link">Products</a></li>
</ul>
</li>
 </ul> 
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

这是我在这种情况下通常做的事情:

&#13;
&#13;
.parent {
    /*....your existing css...*/
    position: relative;
}
.sub-menu {
    display: block;
    left: 50%;
    text-align: center;
    position: absolute;
    transform: translateX(-50%);
}
&#13;
<div class="parent">
  <div class="sub-menu">
    Centered
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

上周我遇到了这个问题,这样的事情解决了我的问题:

li > a {
    ....your existing css...
    position: relative;
}
.sub-menu {
    display: block;
    left: 0;
    right: 0;
    text-align: center;
    position: absolute;
    margin-left: -100%;
    margin-right: -100%;
}

就我而言,.sub-menuli > a宽,但我希望.sub-menu位于li > a下方。这是你遇到的问题吗?