将一个项目放在位置的中心: 相对位置

我有一个菜单,显示悬停在一个绝对定位的 div。所有的菜单项都必须相对定位,因为绝对 div 将在一个页面上出现多次,并且在一个实例中以多种大小出现。

当我不知道父 div 的大小时,如何使用 position: relative在垂直和水平方向上集中多个项目?

我知道负利润的 position: absolute技巧,但这种情况需要一些不同的东西。

密码是这样的:

.OuterCase {
position  : absolute;
width     : 100%;
height    : 100%;
text-align: center;
}


.InnerItem  {
width  : 38px;
height : 38px;
display: inline-block;
}

我让它把物品水平地放在中心,让它垂直,这有点难以捉摸。

258819 次浏览

If you have a relatively- (or otherwise-) positioned div you can center something inside it with margin:auto

Vertical centering is a bit tricker, but possible.

Alternatively, you may also use the CSS3 Flexible Box Model. It's a great way to create flexible layouts that can also be applied to center content like so:

#parent {
-webkit-box-align:center;
-webkit-box-pack:center;
display:-webkit-box;
}

You can use calc to position element relative to center. For example if you want to position element 200px right from the center .. you can do this :

#your_element{
position:absolute;
left: calc(50% + 200px);
}

Dont forget this

When you use signs + and - you must have one blank space between sign and number, but when you use signs * and / there is no need for blank space.

Much simpler:

position: relative;
left: 50%;
transform: translateX(-50%);

You are now centered in your parent element. You can do that vertically too.

Another option is to create an extra wrapper to center the element vertically.

#container{
border:solid 1px #33aaff;
width:200px;
height:200px;
}


#helper{
position:relative;
height:50px;
top:50%;
border:dotted 1px #ff55aa;
}


#centered{
position:relative;
height:50px;
top:-50%;
border:solid 1px #ff55aa;
}
<div id="container">
<div id="helper">
<div id="centered"></div>
</div>
<div>